Access to the path denied error in C#

aerojun picture aerojun · Oct 9, 2011 · Viewed 132.7k times · Source

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;

Answer

Alan picture Alan · Oct 9, 2011

You are trying to create a FileStream object for a directory (folder). Specify a file name (e.g. @"D:\test.txt") and the error will go away.

By the way, I would suggest that you use the StreamWriter constructor that takes an Encoding as its second parameter, because otherwise you might be in for an unpleasant surprise when trying to read the saved file later (using StreamReader).