System.UnauthorizedAccessException:

Kurt

0
Joined
Feb 14, 2003
Messages
113
Location
Los Angeles
I set up the following test in a mini - windows app. The idea is that the code could be used in an ASP.NET project later on. The general problem here is authentication... I have all the user rights to write to the mentioned server, but I dont know how to pass my credentials allong with the write command...

The following is working: (writing to a new or overwriting an existing file locally)

Code:
 private void button1_Click(object sender, System.EventArgs e)
      {
         StreamWriter sw = null;
         try
         {
            sw = File.CreateText(@"C:\new text files\test.txt");
            sw.Write("testing the method again again");
         }
         catch (Exception exc)
         {
            MessageBox.Show(exc.ToString());
         }
         finally
         {
            if (sw != null)
            {
               sw.Flush();
               sw.Close();
            }
         }
      }


not working: (Writing the file to a network share)

Code:
private void button1_Click(object sender, System.EventArgs e)
      {
         StreamWriter sw = null;
         try
         {
            sw = File.CreateText(@"\\10.0.0.20\files$\test.txt");
            sw.Write("testing the method again again");
         }
         catch (Exception exc)
         {
            MessageBox.Show(exc.ToString());
         }
         finally
         {
            if (sw != null)
            {
               sw.Flush();
               sw.Close();
            }
         }
      }

error:
Code:
System.UnauthorizedAccessException: Access to the path "\\10.0.0.20\files$\test.txt" is denied.
Also, mapping the "\\10.0.0.20\files$" folder to a new drive name (for example "Z:\") and using syntax as
Code:
File.CreateText(@"Z:\test.txt");
is not working.

Is there a way to attach some user credentials to the command, so it becomes authorized to write the file?
 
You dont "pass" credentials to the CreateFile() or Write() methods. The credentials used will be the ones under which the thread is running. If you need for the code to access the files and directories in a specific path, you will need to configure file system ACLs to allow the user account under which the process (or thread) is running to access them. In most cases this involves adding the user account youre using, or adding the "ASPNET" account for Windows XP or Windows 2000 or the "Network Service" account for Windows Server 2003 to allow ASP.NET applications to access the files/directories.
 
Thanx Derek,

How to configure the ACLs? Should I make from the ASP.NET account on the server running the project a Domain account, and add that one to the server where the files should be written? Should I then right click the folder for the text files, choose properties and from the security tab add the user there? I guess I m a little confused.

Kurt
 
Back
Top