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