Reputation: 4064
I'm trying to upload files.
When I post a file, I invoke fileUpload action below.
[HttpPost]
public void fileUpload(FormCollection fc)
{
string fileName = "";
string directory = "";
string uploadPath = "~/Files;
if (Request.Files["Filename"] != null && Request.Files["Filename"].ContentLength > 0)
{
try
{
fileName = Path.GetFileName(Request.Files["Filename"].FileName);
directory = Path.Combine(Server.MapPath(uploadPath), fileName);
Request.Files["Filename"].SaveAs(directory);
}
catch (Exception msg)
{
ViewBag.Message = "Failed to upload your file.";
}
}
}
Code above works just fine. But if I try to create a directory and then try to put the target file into the folder...
[HttpPost]
public void fileUpload(FormCollection fc)
{
string baseFolder = "Files";
string yyyy = DateTime.Today.Year.ToString();
string mm = DateTime.Today.Month.ToString();
string fileName = "";
string directory = "";
string uploadPath = "~/" + baseFolder + "/" + yyyy + "/" + mm;
if (Request.Files["Filename"] != null && Request.Files["Filename"].ContentLength > 0)
{
try
{
fileName = Path.GetFileName(Request.Files["Filename"].FileName);
directory = Path.Combine(Server.MapPath(uploadPath), fileName);
if (!System.IO.Directory.Exists(directory))
{
System.IO.Directory.CreateDirectory(directory);
}
Request.Files["Filename"].SaveAs(directory);
}
catch (Exception msg)
{
ViewBag.Message = "Failed to upload your file.";
}
}
This gives me a following error
E:\Monarch815MVC\Monarch815MVC\Files\2014\12\me.png' Access to the path is denied.
The dynamically generated folders are very suspicious aren't they?
Is there something I missed? Is there something I have to add for the access privilege?
I've googled this issue and found none. They are all talking about "you should give full permission to the folder",
which is not the answer for me.
Upvotes: 0
Views: 1596
Reputation: 14624
You are doing a mistake in your code you are creating directory with the name of file which is wrong
fileName = Path.GetFileName(Request.Files["Filename"].FileName);
directory = Path.Combine(Server.MapPath(uploadPath), fileName);
this will create directory like this and consider file name as folder
E:\Monarch815MVC\Monarch815MVC\Files\2014\12\me.png
change this line like below
directory = Server.MapPath(uploadPath);
You need to combine path where you are uploading file not when creating the directory
Request.Files["Filename"].SaveAs(Path.Combine(directory, fileName));
Upvotes: 1