Exception: "Access to the path ... is denied"

Jeff picture Jeff · Apr 1, 2014 · Viewed 10.7k times · Source

I'm working on a program in C#, a part of which is to create a directory in the Application.StartupPath folder and then write a text file inside it using System.IO.File.WriteAllText(). My issue is that my program crashes, throwing an UnauthorizedAccessException and telling me that "Access to the path is denied", which is, well, odd, considering that it crashes regardless of the directory from which I am running the program, whether it be running from my cloud folders, Desktop, My Documents, etc, and even despite running it as Administrator in any of those directories.

The path from which I'm debugging it is C:\Users\Jeff\Google Drive\Documents\Visual Studio 2013\Projects\Palobo\Palobo\bin\Debug. It is using System.IO;, and the code I'm using includes:

Directory.CreateDirectory(Application.StartupPath);
File.WriteAllText(Application.StartupPath, "Password=" + x);

where x is some String data entered by the user.

The error I get is:

Access to the path 'C:\Users\Jeff\Google Drive\Documents\Visual Studio 2013\Projects\Palobo\mzdon29 is denied.

(mzdon29 being an encrypted result of jwalk96).

Does anyone have any ideas as to why I'm encountering this problem? Thanks!

Answer

nXu picture nXu · Apr 1, 2014

Application.StartupPath is a folder (where your application is started from). Try to specify an exact filename inside that folder:

File.WriteAllText(Application.StartupPath + "\\MyFile.txt", "Password=" + x);