Reputation: 6866
I am currently working on a website which is developed in asp. One page allows users to send messages and upload files. The file gets uploaded and I can save it to a directory no problem. However the client requires a directory to be created for each logged in user and then to save the uploaded file to that particular directory. I have managed to created the directory using the following code.
if (!Directory.Exists("\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId()))
{
Directory.CreateDirectory("\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId());
}
The directory gets created as required. However I can't seem to save the file to that particular directory. Instead it saves the file to the uploads directory. Does anyone know how I can do that. Thanks in advance
My code for saving the file
FileUpload1.SaveAs("\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId()));
Upvotes: 0
Views: 157
Reputation: 3238
I suppose you must change your code to be as follow:
FileUpload1.SaveAs(Server.MapPath("pathtodirectory" + FileUpload1.FileName));
Upvotes: 0
Reputation: 8598
Your solution:
string targetPath = "\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId());
string filePath = Path.Combine(targetPath, Server.HtmlEncode(FileUpload1.FileName));
FileUpload1.SaveAs(filePath);
Upvotes: 0
Reputation: 3329
I think you are missing file name in FileUpload1.SaveAs(...)
method. According to MSDN you need to retrieve FileUpload1.FileName
.
Upvotes: 0
Reputation: 151594
Clean up the code to create the directory by introducing a variable:
string userDirectory = "\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId();
if (!Directory.Exists(userDirectory))
{
Directory.CreateDirectory(userDirectory);
}
And then when saving to that directory, make sure to specifiy a filename instead of a directory:
string filename = Path.Combine(userDirectory, FileUpload1.Filename);
FileUpload1.SaveAs(filename);
See Don't overwrite file uploaded through FileUpload control to make sure you don't overwrite files having the same name.
Upvotes: 4