Emetrop
Emetrop

Reputation: 322

Denied acces to a file

I have a code which is similar this:

string file;

using (StreamReader r = new StreamReader("xml.xml"))
{
    file = r.ReadToEnd();
}

XElement xml = XElement.Parse(file);

using (XmlWriter w = XmlWriter.Create("xml.xml")) //The point of problem!
{
    w.WriteStartDocument();
    ...;
    w.WriteEndDocument();
}

When I try run it like a console application is everything all right. But problems start when I want to use it in an ASP.NET application. At the using line it throws UnauthorizedAccessException exception with a description "access to the path is denied". Why?

Upvotes: 0

Views: 234

Answers (2)

Markus
Markus

Reputation: 22421

If IIS/the web server is configured correctly, an account with a very limited set of permissions is used. As your path points to the application directory, it is very likely that the application pool account is not allowed to write to this location.
If you run the code in a console application, your user's permissions are applied and it is more than likely that you are allowed to write to the output folder of the project as Visual Studio writes the build output there under your account.
I would not recommend to change the application pool account or the permissions of the application folder in the file system - it is a very sensible limitation that limits the amount of trouble an attacker can possibly make.
Therefore I'd recommend to either move the file to a folder that the account can write to without changing permissions or define a special one outside of the application folder hierarchy that the account is given permissions to.
Also keep in mind that multiple users might access the file at the same time, so a database might be a better choice to store the data.

Upvotes: 0

Lucas Rodrigues Sena
Lucas Rodrigues Sena

Reputation: 399

You need to check which account your application Pool is using to access your server files/folders, for example, make one code to copy one file to application folder, check all security info, copy and paste on this problem folder, normally use this account "IIS_IURRS" give full control to test only...

Upvotes: 2

Related Questions