代码之家  ›  专栏  ›  技术社区  ›  Lucy

在使用StreamWriter时,我遇到了错误;访问被拒绝[关闭]

  •  -1
  • Lucy  · 技术社区  · 8 年前

    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 回复  |  直到 8 年前
        1
  •  2
  •   Lifewithsun    8 年前

    您忘记指定文件路径。

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