Reputation: 237
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!
Upvotes: 4
Views: 17884
Reputation: 416131
Let's look at this code:
Directory.CreateDirectory(Application.StartupPath);
File.WriteAllText(Application.StartupPath, "Password=" + x);
You're trying to create a directory that already exists, and then you're trying use the directory as a file name! You need to add something to end of the path, so that you're working with a new folder and file.
Also, using the StartupPath for this is poor practice in the first place. You can create a shortcut that sets the startup path to anywhere. But specifically, it's common for the default StartupPath to be somewhere under the Program Files folder. Items under this folder are read only to standard users by default. Instead, you should look at using the Application Data folder, like so:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Finally, this sure looks like it's saving a password in plain-text. Do I really need to go over how bad that is? You shouldn't even save passwords encrypted (hashing is different than encryption), and this is one of those things that's so important you shouldn't even do it for testing/learning/proof of concept code.
Upvotes: 5
Reputation: 2272
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);
Upvotes: 9