-1

When my code runs in case DialogResult.No:, I am getting the error:

access is denied

This is my code:

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

The error appears to be to do with the StreamWriter.

Bugs
  • 4,491
  • 9
  • 32
  • 41
Lucy
  • 31
  • 1
  • 2

1 Answers1

2

You forgot to specify the file path.

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

It will create abc text file for you.If you have aleary file created then you have to just specify the exact path and set it true.

Syntax:

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

Example:

new System.IO.StreamWriter(desktopPath+"\\abc.text",true);
Lifewithsun
  • 968
  • 14
  • 34