在使用 StreamWriter 时出现错误;访问被拒绝

Whilst using StreamWriter I am getting the error; access is denied

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

access is denied

这是我的代码:

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 有关。

您忘记指定文件路径。

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

它将为 you.If 创建 abc 文本文件,您已经创建了 aleary 文件,然后您只需指定确切的路径并将其设置为真。

语法:

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

示例:

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