ASP.NET - Exception in file write, but file is written okay.

Asked By Patrick Skelton on 21-Aug-13 05:05 AM
Hi,

I have what I believe is an odd problem.  I am using the code given below to write to a pre-existing file.  The write appears to happen okay.  Copying the path into Notepad also allows the file to be viewed and edited okay.  Nevertheless, the function gives an AccessDenied exception.  Bit puzzled by this one.  Does anyone have any idea what might be happening?

using( StreamWriter streamWriter = File.AppendText( "D:\...\Log.txt" ) )
{
  streamWriter.Write( WebUtility.FixSingleNewline( "Some text." ) );
}

An update on the problem...

This code is actually being used in an ASP.NET website on my local machine.  It seems I can make writes to the file in the Global Application_Start event, but when I try to call the code from a page, I get Access Denied.  Do these two locations operate with different permission levels?

Kind wishes ~ Patrick

PS - I suspect I need to move this to the ASP.NET forum, but don't know how.  Sorry.
Robbe Morris replied to Patrick Skelton on 21-Aug-13 07:08 AM

Use the FileStream class to make sure you've got all the file modes and access settings done correctly.  Then, make sure that whatever folder/path you are writing to is granted Write access to the windows account your IIS application pool is running under.  Most likely the Network Service account.

using (FileStream f = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write))

{

using (StreamWriter w = new StreamWriter(f))

{

w.WriteLine("stuff");

}

}

Patrick Skelton replied to Robbe Morris on 21-Aug-13 07:41 AM
Thanks for that, Robbe.  I have now solved it by granting Write permission to the folder for the IIS_IUSR account.  Given that this folder is a subdirectory in the Visual Studio project, I would have thought Visual Studio might do this as part of creating a new project.  I can't even find any documentation about needing to do this.

Maybe I'm missing something, but it works locally now, and I am hoping that my hosting providers will have set things up so I don't hit the same problem on the live server.

Thanks for the reply.

Kind wishes ~ Patrick