nerd
nerd

Reputation: 369

DirectoryNotFoundException error while copying the file

I am trying to develop a web application which will send a file to the server (in this case the server is a local one). However when I try to send the file, it always gives:

DirectoryNotFoundException: Could not find part of the path.

I have verified that the folder actually exists. And to ensure, I create the Directory before copying but I still get the error. Could anyone help please? Here is the code:

string FileName = System.IO.Path.GetFileName("c:\\test\\Sample.txt");
string SaveLocation = HttpContext.Current.Server.MapPath("Uploadfile") + "\\";

if (System.IO.Directory.Exists(SaveLocation))
{
     System.IO.Directory.CreateDirectory(SaveLocation);
     System.IO.File.Copy("C:\\test\\Sample.txt", SaveLocation, true);
}

The value of SaveLocation is:

C:\Users\Nerd\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\Uploadfile\

Upvotes: 0

Views: 3050

Answers (1)

Tasos K.
Tasos K.

Reputation: 8077

The System.IO.File.Copy needs its second argument to be a path to a file and not a path to a directory. Adjust your code to include the name you want the file to be saved.

string FileName = System.IO.Path.GetFileName("c:\\test\\Sample.txt");
string SaveLocation = HttpContext.Current.Server.MapPath("Uploadfile") + "\\";

if (System.IO.Directory.Exists(SaveLocation))
{
     System.IO.Directory.CreateDirectory(SaveLocation);
     System.IO.File.Copy("C:\\test\\Sample.txt", SaveLocation + "Sample.txt", true);
}

Upvotes: 5

Related Questions