creating nested folder in c# shows access denied error - c#

I am trying to create folders in nested manner.
if (file.ContentLength > 0 && file != null)
{
string path = "~/Videos/" + Session["username"] + "_" + Session["userid"];
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filename = path + file.FileName;
filepath = "/Videos/" + Session["username"] + "_" + Session["userid"];
file.SaveAs(filename);
If you see here- /Videos/ folder is what I have currently on disk. Where another folder with user's name and id is what I want to create inside this Videos folder. How Would I be creating this folder inside this folder?
Because currently it is showing me this error -
Access to the path '~/Videos/shaun_2' is denied.
I tried restarting visual studio with administrator's credentials. But it still remains here.

I'm assuming that you are using ASP.NET: try to use Server.MapPath("~/...") to get the physical path
See MSDN

Related

Directory.Move fails while copying files 1 by 1 works

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:
Why am I still getting "Access to the path 'C:\...\...' is denied" even after granting IIS_IUSRS write permission on the directory?
Access to path denied on IIS
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.

Could not find a part of the path C# asp.net when I generated user session folder in particular directory

string UserFolder = Session["Username"].ToString();
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
filePathE = Server.MapPath("~/MisReports/EmailAttachment/" + UserFolder + "/");
filePathE = filePathE + a + ".pdf";
bool isExist = File.Exists(filePathE);
if (isExist)
{
File.Delete(filePathE);
}
report.ExportToDisk(ExportFormatType.PortableDocFormat, filePathE);
I get the error
Could not find a part of the path
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
in this area code does not enter if check although that the folder has not been created
The ~ is probably not evaluated if you are running on Windows. Windows is not Unix. Read up on Path.Combine, Environment.GetFolderPath and Environment.SpecialFolder on MSDN. You should build a path with code like
string directoryName = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "MisReports/EmailAttachment", UserFolder);

Add date stamp on uploaded file

I'm currently developing a website using asp and c#. One of the pages allows registered users to upload files. These files get stored according to the user who is logged in. A directory is created when they hit upload with there login name and id.
string userDirectory = "\\Test\\Files\\ " + User.Identity.Name + " " + User.Identity.GetUserId();
if (!Directory.Exists(userDirectory))
{
Directory.CreateDirectory(userDirectory);
}
The directory gets created without an issue and file also gets uploaded. However the problem I am now facing is I'm trying to add a date stamp to a file if it already exist in the directory so I don't overwrite it. See the code below
string fileName = Path.Combine(userDirectory, FileUpload1.FileName);
if (!File.Exists(fileName))
{
FileUpload1.SaveAs(fileName);
}
else
{
fileName = string.Concat(
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("_yyyy_MM_dd_HH:mm:ss"),
Path.GetExtension(fileName)
);
FileUpload1.SaveAs(fileName);
}
This keeps giving me an error:
System.Web.HttpException: The SaveAs method is configured to require a rooted path, and the path 'Test.docx' is not rooted
Does anyone know where I'm going wrong? Thanks in advance
You have to append the directory name to the path, since you stripped it off (by using GetFileNameWithoutExtension):
string newFileName =
Path.Combine( Path.GetDirectoryName(fileName)
, string.Concat( Path.GetFileNameWithoutExtension(fileName)
, DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss")
, Path.GetExtension(fileName)
)
);
Also note that using : in a file name is not supported, so I replace it with _.

ASP.NET: Trying to rename a file but getting "Access to path" denied errors

The odd thing is that something like System.IO.File.Delete() works
and the file gets deleted but will give "access to path is denied error" for .Move() operation.
All files are located in the same folder, user "Network service" has all
full control rights for the folder and all subfolders in it etc.
Folders are located in the project directory and can be seen in solution explorer.
Exception Details: System.UnauthorizedAccessException: Access to the path is denied.
foreach(var info in FileActions.Where(x => x.OldSortOrder != x.SortOrder))
{
string FileToRename;
string NewName;
string OldFilePath;
string OldFileThumbPath;
FileToRename = info.ProductID + "/" + info.OldSortOrder + "-" + info.ImageID + ".jpg";
NewName = info.SortOrder + "-" + info.ImageID + ".jpg";
OldFilePath = System.Web.HttpContext.Current.Request.MapPath("~/Content/ProductImages/" + FileToRename);
OldFileThumbPath = System.Web.HttpContext.Current.Request.MapPath("~/Content/ProductImages/" + info.ProductID + "/thumbs/" + FileToRename);
System.IO.File.Move(OldFilePath, NewName);
System.IO.File.Move(OldFileThumbPath, NewName);
}
Its because you map the path for the first files but not for the NewName.
So did not have the full path to know what to rename/move the file, and needs the full path to work correctly.
With out the path this is probably try to move it on the default folder of the asp.net pool that is probably don't have this permissions.
So the code will be
NewName = System.Web.HttpContext.Current.Request.MapPath("~/Content/ProductImages/"
+ info.SortOrder + "-" + info.ImageID + ".jpg" );
and debug this lines to see if the directories and files are all correct.

Process.Start is not working after hosting asp.net web application in IIS

I have a return a c# code to save a file in the server folder and to retrieve the saved file from the location. But this code is working fine in local machine. But after hosting the application in IIS, I can save the file in the desired location. But I can't retrieve the file from that location using
Process.Start
What would be the problem? I have searched in google and i came to know it may be due to access rights. But I don't know what would be exact problem and how to solve this? Any one please help me about how to solve this problem?
To Save the file:
string hfBrowsePath = fuplGridDocs.PostedFile.FileName;
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\\\";
if (!Directory.Exists(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)))
Directory.CreateDirectory(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1));
FileInfo FP = new FileInfo(hfBrowsePath);
if (hfFileNameAutoGen.Value != string.Empty)
{
string[] folderfiles = Directory.GetFiles(FilePath);
foreach (string fi in folderfiles)
File.Delete(fi);
//File.Delete(FilePath + hfFileNameAutoGen.Value);
}
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value;
//File.Copy(hfBrowsePath, destfile, true);
fuplGridDocs.PostedFile.SaveAs(destfile);
}
To retrieve the file:
String filename = lnkFileName.Text;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\";
FileInfo fileToDownload = new FileInfo(FilePath + "\\" + filename);
if (fileToDownload.Exists)
Process.Start(fileToDownload.FullName);
It looks like folder security issue. The folder in which you are storing the files, Users group must have Modify access. Basically there is user(not sure but it is IIS_WPG) under which IIS Process run, that user belongs to Users group, this user must have Modify access on the folder where you are doing read writes.
Suggestions
Use Path.Combine to create folder or file path.
You can use String.Format to create strings.
Create local variables if you have same expression repeating itself like FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)
Hope this works for you.
You may have to give permissions to the application pool that you are running. see this link http://learn.iis.net/page.aspx/624/application-pool-identities/
You can also use one of the built-in account's "LocalSystem" as application pool identity but it has some security issue's.

Categories