Question

I need to create a folder to use for storing files within it, in a .Net MVC3 application, but I think the problem is common to all ASP.Net platform. Problem is I can create the folder, but cannot write the files, because System.UnauthorizedAccessException occurred. I also tryed givin extra permission to the user currently running the web app, but nothing changes. This is my code so far:

if (!System.IO.Directory.Exists(fullPath))
{
    System.IO.Directory.CreateDirectory(fullPath);                    
    var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
    var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
    var dirInfo = new System.IO.DirectoryInfo(fullPath);
    var sec = dirInfo.GetAccessControl();                    
    sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
                    System.Security.AccessControl.FileSystemRights.Modify,
                    System.Security.AccessControl.AccessControlType.Allow)
                    );
    dirInfo.SetAccessControl(sec);                    
    System.IO.Directory.CreateDirectory(fullPath);                    
}
string fullPathFileName = System.IO.Path.Combine(fullPath, fileName);                
System.IO.File.WriteAllBytes(fullPath, viaggio.Depliant.RawFile);

Too bad, last line of code always throw System.UnauthorizedAccessException. I'm not impersonating user in my app, everything run under a predefined user. What should I do to create a folder and assure that the application can also create files within it?

Edited:

I also tryed to save the files in the App_Data special folder, but I still got the System.UnauthorizedAccessException error. Somebody can tell me why is that happening?

Was it helpful?

Solution

I hate to answer my own question when the problem is that stupid... I'm just trying to save a file without a proper filename: you can see I'm using the fullPath variable both for creating the folder and for saving the file, instead of using the correctly created fullPathFileName. Blame on me!

OTHER TIPS

Use App_Data folder, quote from http://msdn.microsoft.com/en-us/library/06t2w7da%28v=vs.80%29.aspx :

To improve the security of the data used by your ASP.NET application, a new subfolder named App_Data has been added for ASP.NET applications. Files stored in the App_Data folder are not returned in response to direct HTTP requests, which makes the App_Data folder the recommended location for data stored with your application, including .mdf (SQL Server Express Edition), .mdb (Microsoft Access), or XML files. Note that when using the App_Data folder to store your application data, the identity of your application has read and write permissions to the App_Data folder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top