tags:

views:

137

answers:

1

I'm using a SaveFileDialog to let a user pick a directory and filename on a removeable drive. Afterwards I create that file, write to it, and close it again.

By then the file itself is not locked (editable, deleteable), but I can't eject the drive because windows claims it is still in use. I have to exit the application before an eject is possible.

Incidentally the drive gets locked even when I only pick the file with the SaveFileDialog. Hitting "Cancel" on the dialog doesn't cause the problem

SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = ".csv";
dlg.InitialDirectory = mySettings.defaultPath;
dlg.Filter = "(CSV-Dateien) *.csv|";
dlg.FileName = exportDate.ToString("yyyy-MM-dd") + ".csv";

if (dlg.ShowDialog() != DialogResult.OK){
    // USB-Drive is ejectable
}else{
    // USB-Drive is locked
}
+1  A: 

I found 2 Solutions:

The Dialog changes the current working directory once the user clicks "save". It's not the file that was blocking the removable drive, but the program itself .

So you either need to readjust the working directory once you're done:

String oldDir = Directory.GetCurrentDirectory();
// ... do dialog...
Environment.CurrentDirectory = oldDir;

or you simply configure the file dialog to restore the directory before calling ShowDialog()

dlg.RestoreDirectory = true;
dlg.ShowDialog()
stew
nice work, thanks for posting the final answer
Michael Haren