Search code examples
c#savefiledialog

Prevent app from crashing if the file is already when saving to a .csv


I currently have the code below to save some data to a .csv file. Everything works properly, but the one problem I am having is if the .csv file is open, and you try to save a new set of data the app crashes. I think making it a read only will prevent this problem, but i am not sure how to do that. For example. if the last file is saved at C:\Users\Documents\data.csv, and the user has that data.csv file open. Then the user saves another set of data using the same path, the app then crashes.

SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = tbSave.Text;
saveFileDialog.Filter = ".csv|*.csv";
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
    File.WriteAllText(saveFileDialog.FileName, sb.ToString());
    MessageBox.Show("Save Complete!" + "\n" + "Number of skips recorded: " + skips.ToString() + "\n" + "Elasped time recorded (ms): " + time.ToString());
}

Solution

  • I made the saved file a read only. This ensures it can't be written over, and the app won't crash if the excel file is open. Within the context of my purpose this solution works fine.

    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.FileName = tbSave.Text;
    saveFileDialog.Filter = ".csv|*.csv";
    if(saveFileDialog.ShowDialog() == DialogResult.OK)
    {    
        File.WriteAllText(saveFileDialog.FileName, sb.ToString());
        File.SetAttributes(saveFileDialog.FileName, FileAttributes.ReadOnly);
        MessageBox.Show("Save Complete!" + "\n" + "Number of skips recorded: " + skips.ToString() + "\n" + "Elasped time recorded (ms): " + time.ToString());
    }