使用StreamWriter时,我收到错误;访问被拒绝

时间:2017-08-01 07:38:38

标签: c# streamwriter access-denied

当我的代码在case DialogResult.No:中运行时,我收到错误:

  

访问被拒绝

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    var message = "Love?";
    var title = "Love?";
    var result = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    switch (result)
    {
        case DialogResult.Yes:
            MessageBox.Show("Love!");
            break;
        case DialogResult.No:
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string text2write = "LOVE";
            System.IO.StreamWriter writer = new System.IO.StreamWriter(desktopPath);
            writer.Write(text2write);
            writer.Close();
            break;  
    }
}

该错误似乎与StreamWriter

有关

1 个答案:

答案 0 :(得分:2)

您忘了指定文件路径。

string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string text2write = "LOVE";
System.IO.StreamWriter writer = new System.IO.StreamWriter(desktopPath+"\\abc.txt");
writer.Write(text2write);
writer.Close();

它将为您创建abc文本文件。如果您创建了aleary文件,则必须指定确切的路径并将其设置为true。

语法:

new System.IO.StreamWriter(string path,bool append);

示例:

new System.IO.StreamWriter(desktopPath+"\\abc.text",true);