C# Unable to overwrite file contents when file extension is .txt

84 Views Asked by At

I am attempting to write a string to a file that the user specifies using the SaveFileDialog component.

The output file is created and populated successfully if it does not already exist. However, if the file does exist, and has a file extension, then a System.UnauthorisedAccessException is produced stating that Access to the path 'C:\Users\mmark\Desktop\Output.txt' is denied.

I have tested with outputting files with .csv and .txt file extensions, and no file extennsion, and it has only updated a file successfully if it doesn't have a file extension.

I have tried:

  • Using StreamWriter.Write to output the file.
  • Using FileStream.Write to output the file.
  • Using File.WriteAllText to output the file.
  • Setting the file attributes to normal to remove read-only before trying any of the above methods again.

The following is the code I have used for writing the string to the file, with some of the other attempts commented out to show what I attempted to do. Any assistance would be appreciated:

private void SaveFileBtn_Click(object sender, EventArgs e)
{
    SaveFileDialog dialog = new SaveFileDialog();

    if (dialog.ShowDialog() == DialogResult.OK) {
        try {
            //if(File.Exists(dialog.FileName)) {
            //     File.SetAttributes(dialog.FileName, FileAttributes.Normal);
            //}

            File.WriteAllText(dialog.FileName, richTextBox1.Text);

            //using (StreamWriter writer = new StreamWriter(dialog.FileName)) {
            //    writer.Write(richTextBox1.Text);
            //}

            //using (FileStream fs = File.Create(dialog.FileName)) {
            //    byte[] info = new UTF8Encoding(true).GetBytes(richTextBox1.Text);
            //    fs.Write(info, 0, info.Length);
            //}

            MessageBox.Show("File Created!");
        } catch(Exception err) {
            MessageBox.Show("File Creation Error: " + err);
        }
    }
}
1

There are 1 best solutions below

0
M Markov On

In this specific scenario, the issue was caused by access rights on the C:\Users\mmark directory, and resolved by saving the file to a different folder outside of the C:\Users\mmark directory.

Whilst it didn't occur in this scenario, a possible cause for the issue would also have been if the file was previously opened earlier in the application or by another application, and still open at the time of the save attempt.