[c#] Access to the path denied error in C#

I have read a similar post, but i just cant figure out the problem.

I have changed the windows permissions and changed routes.

When i try to save a file it throws me the exception:

Access to the path **** denied.

string route="D:\\";
FileStream fs = new FileStream(route, FileMode.Create); <--here is the problem
        StreamWriter write = new StreamWriter(fs);
        patient person = new patient();
        patient.name = textBox1.Text;
        patient.name2 = textBox2.Text;

This question is related to c# filestream access-denied

The answer is


If your problem persist with all those answers, try to change the file attribute to:

File.SetAttributes(yourfile, FileAttributes.Normal);

I had this issue for longer than I would like to admit.

I simply just needed to run VS as an administrator, rookie mistake on my part...

Hope this helps someone <3


You do not have permissions to access the file. Please be sure whether you can access the file in that drive.

string route= @"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);

You have to provide the file name to create. Please try this, now you can create.


tl;dr version: Make sure you are not trying to open a file marked in the file system as Read-Only in Read/Write mode.

I have come across this error in my travels trying to read in an XML file. I have found that in some circumstances (detailed below) this error would be generated for a file even though the path and file name are correct.

File details:

  • The path and file name are valid, the file exists
  • Both the service account and the logged in user have Full Control permissions to the file and the full path
  • The file is marked as Read-Only
  • It is running on Windows Server 2008 R2
  • The path to the file was using local drive letters, not UNC path

When trying to read the file programmatically, the following behavior was observed while running the exact same code:

  • When running as the logged in user, the file is read with no error
  • When running as the service account, trying to read the file generates the Access Is Denied error with no details

In order to fix this, I had to change the method call from the default (Opening as RW) to opening the file as RO. Once I made that one change, it stopped throwing an error.


Did you try specifing some file name?

eg:

string route="D:\\somefilename.txt";