Daniel Hamutel
Daniel Hamutel

Reputation: 653

Why am I getting file access denied trying to make a StreamWriter instance?

string pathDir = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\settings";
string settingsFile = "settings.txt";
StreamWriter w;

public Form1()
{
    InitializeComponent();

    if (!Directory.Exists(Path.Combine(pathDir, settingsFile)))
        Directory.CreateDirectory(Path.Combine(pathDir, settingsFile));
    settingsFile = Path.Combine(pathDir, settingsFile);
    w = new StreamWriter(settingsFile, true);

The exception is on the line:

w = new StreamWriter(settingsFile, true);

Access to the path 'C:\Users\bout0_000\AppData\Local\Grads_Scripts\Grads_Scripts\settings\settings.txt' is denied

And now i moved the instance of the StreamWriter to a textBox1_TextChanged event:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            w = new StreamWriter(settingsFile, true);
            w.Write(textBox1.Text);
            w.Close();
        }

I want to write the text i type in the textBox1 in real time to the text file. Without a button click confirm or something but in real time. While i'm typing it will write it to the text file. But the way it is now i see in the text file everything i typed many times the same.

Upvotes: 0

Views: 3012

Answers (1)

Ryan Emerle
Ryan Emerle

Reputation: 15821

I appears you are creating a directory named [...]\Grads_Scripts\settings\settings.txt then trying to write to it as a file. Go to the directory C:\Users\bout0_000\AppData\Local\Grads_Scripts\Grads_Scripts\settings\ and see if there is a folder called settings.txt. If so, delete it and modify your code to create the parent directory only.

You should be able to change your code as follows:

string pathDir = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\settings";
string settingsFile = "settings.txt";
StreamWriter w;

public Form1()
{
    InitializeComponent();

    // Create the parent directory if it doesn't exist
    if (!Directory.Exists(pathDir)) 
        Directory.CreateDirectory(pathDir);
    settingsFile = Path.Combine(pathDir, settingsFile);
    w = new StreamWriter(settingsFile, true);
}

Remember to wrap your StreamWriter in a using statement (or call Dispose manually) so that the file resources are released after you've finished writing.

using( w = new StreamWriter(settingsFile, true) ){
    // Write to stream writer
}

Upvotes: 3

Related Questions