为什么我尝试创建StreamWriter实例时拒绝文件访问?

时间:2015-12-21 16:09:55

标签: c# .net winforms

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);

例外是在线:

w = new StreamWriter(settingsFile, true);
  

访问路径' C:\ Users \ bout0_000 \ AppData \ Local \ Grads_Scripts \ Grads_Scripts \ settings \ settings.txt'被拒绝

现在我将StreamWriter的实例移动到textBox1_TextChanged事件:

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

我想将textBox1中的文本实时写入文本文件。没有按钮点击确认或实时,但实时。虽然我输入它会将其写入文本文件。但是现在的方式我在文本文件中看到我输入的内容多次相同。

1 个答案:

答案 0 :(得分:2)

我看来你正在创建一个名为[...]\Grads_Scripts\settings\settings.txt的目录,然后尝试将其作为文件写入。转到目录C:\Users\bout0_000\AppData\Local\Grads_Scripts\Grads_Scripts\settings\,看看是否有名为settings.txt的文件夹。如果是这样,请将其删除并修改代码以仅创建父目录。

您应该可以按如下方式更改代码:

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);
}

请记住将StreamWriter包装在using语句中(或手动调用Dispose),以便在完成编写后释放文件资源。

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