SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6056

Error in Copying File using C#

I have a .aspx page which creates HTML file dynamically on Button click. The .html page gets created successfully but, not able to copy the created file to the destination using File.Copy method.

Code Behind:

 protected void btnPublish_Click(object sender, EventArgs e)
    {
        //copy the created file content to destination
         string sourcePath=string.Empty;
         string destiPath = @"d://test//";
        if(!string.IsNullOrEmpty(hdnPublishPath.Value))
        { 
            sourcePath= hdnPublishPath.Value;
            if (!Directory.Exists(destiPath)) // check if folde exist
            {
                Directory.CreateDirectory(destiPath); // create folder
                //Directory.Delete(destiPath, true);  // delete folder
            }

            File.Copy(sourcePath, destiPath,true);
        }
    }

It gives exception:Directory not found exception.

enter image description here

The directory gets created on mentioned drive(D:/) but the file copy fails.

NOTE: Currently the path is of "local" but later on this file will be copied to any remote server location

Upvotes: 0

Views: 2702

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

There's a syntax error in destiPath:

  ... 
  // That's incorrect:
  // string destiPath = @"d://test//";

  // Should be like this
  string destiPath = @"d:\test\";
  // ... or like that
  string destiPath = "d:\\test\\";
  ...

Another issue with File.Copy: you should provide file names, not directory names:

  ...
  // Incorrect 
  // File.Copy(sourcePath, destiPath,true);

  // Should be something like
  File.Copy(Path.Combine(sourcePath, "myFile.txt"), Path.Combine(destiPath, "myFile.txt"), true);

Upvotes: 2

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

You will want to have the path and file name as your destination, not the directory:

File.Copy(sourcePath, Path.Combine(destiPath, filename));

If you supply only the target directory, you will get the exception that you get now.

Upvotes: 1

Neel
Neel

Reputation: 11721

You need to give path as below as you do not need to add "@" or you can simply write @"d:/test/" :-

protected void btnPublish_Click(object sender, EventArgs e)
    {
        //copy the created file content to destination
         string sourcePath=string.Empty;
         string destiPath = "d://test//";
        if(!string.IsNullOrEmpty(hdnPublishPath.Value))
        { 
            sourcePath= hdnPublishPath.Value;
            if (!Directory.Exists(destiPath)) // check if folde exist
            {
                Directory.CreateDirectory(destiPath); // create folder
                //Directory.Delete(destiPath, true);  // delete folder
            }

            File.Copy(sourcePath, destiPath,true);
        }
    }

For more information have a look :-

http://msdn.microsoft.com/en-us/library/362314fe.aspx

Upvotes: 0

Related Questions