I have an ASP.NET MVC application, hosted on IIS 8, windows server 2012 and I upload some files to a temporary directory. After doing some other work, all these files are moved to a concrete directory. My question is why doesn't Directory.Move
work while FileInfo.CopyTo
works.
Directory.Move
fails with
"Access to the path 'serverPath...' is denied."
Code I'm using to move entire directory:
var pathFrom = Server.MapPath("~/Uploads/Objects/" + tempFolderName); //tempFolderName is a random generated GUID.
var pathTo = Server.MapPath("~/Uploads/Objects/" + ObjectId); //ObjectId is an integer
if (Directory.Exists(pathFrom))
{
Directory.Move(pathFrom, pathTo);
}
To create a temporary directory I'm simply calling: Directory.CreateDirectory(path)
which works and creates the temporary directory, and files are saved inside it.
Method I use to copy files, one by one, which works:
public static void DirectoryCopy(string strSource, string Copy_dest)
{
DirectoryInfo dirInfo = new DirectoryInfo(strSource);
DirectoryInfo[] directories = dirInfo.GetDirectories();
FileInfo[] files = dirInfo.GetFiles();
foreach (DirectoryInfo tempdir in directories)
{
Console.WriteLine(strSource + "/" + tempdir);
Directory.CreateDirectory(Copy_dest + "/" + tempdir.Name);// creating the Directory
var ext = System.IO.Path.GetExtension(tempdir.Name);
if (System.IO.Path.HasExtension(ext))
{
foreach (FileInfo tempfile in files)
{
tempfile.CopyTo(Path.Combine(strSource + "/" + tempfile.Name, Copy_dest + "/" + tempfile.Name));
}
}
DirectoryCopy(strSource + "/" + tempdir.Name, Copy_dest + "/" + tempdir.Name);
}
FileInfo[] files1 = dirInfo.GetFiles();
foreach (FileInfo tempfile in files1)
{
tempfile.CopyTo(Path.Combine(Copy_dest, tempfile.Name));
}
}
What I tried to make Directory.Move
work:
- Checked to see if directory
pathTo
doesn't exist - Checked to see if IIS has required permissions:
IISAppPool/DefaultAppPool
has full access to the Uploads folder. - Tried to check with Process monitor if any other error comes up but it seems that this doesn't even get logged.
- Closed every explorer.
Can anyone explain why Directory.Move
doesn't work (with the access deny error) while moving the files one by one works?
Does Directory.Move
require more privileges than just copying files 1 by 1?
Please be aware that the application is not under wwwroot... but on other drive.
Pages I already read:
IOException access denied when Directory.Move subfolder and parent folder
EDIT
After copying the files using FileInfo.Copy
I delete the tempFolder with Directory.Delete(pathFrom, true);
which also works.