Search code examples
c#asp.netpermission-denied

Can't create a file in C:\inetpub\wwwroot programmatically


I have a function in the code behind of an ASP.NET webpage that creates a file and then opens it with a javascript command. This works in the IDE - it creates the file, asks me where I want to save the file, I can save it, etc. - but when I install the website and test it out, I get an UnauthorizedAccessException while just trying to create the directory for the file within C:\inetpub\wwwroot.

The frustrating part is that I have a similar function that runs in a service and that creates its directories and files just fine in C:\inetpub\wwwroot.

What would I have to do to get this to work for a webpage?

 if(!Directory.Exists(directory))
 {
      Directory.CreateDirectory(directory);
 }

 StreamWriter SW = new StreamWriter(fullpath, false, Encoding.Unicode);

 SW.WriteLine(/*stuff*/);

 SW.Close();

Solution

  • You need to make sure the .NET user has write access by right-clicking on the directory, going to the security tab, and adding the appropriate user and checking the write checkbox.

    Depending on your version of .NET/Windows/IIS this can be different, typically it is Network Service or IUSR. If you are running IIS7 make sure to check the Identity under advanced settings of the application pool, as that will be the user that needs the write access, again typically this is Network Service.