Tuesday, July 08, 2008

Microsoft.Win32.OpenFileDialog affect FileIO operation

Just found out that if I use the following code to retrieve a filename, the FileStream will be affected as the current directory will be set to where the filename was taken from, eg.: "My Documents", instead of the Application Path.

OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "All files (*.*)|*.*";
if ((bool)dialog.ShowDialog())
{
// store filename
}

// and later in the code
FileStream stream = new FileStream(
"mydata.bin", FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
// write some data
stream.Close();
// "mydata.bin" will be saved in the current directory of OpenFileDialog

One solution will be to use the application path and extract the directory:
String path = System.Reflection.Assembly.GetExecutingAssembly().Location;

another will be to use RestoreDirectory property of the OpenFileDialog. set it to true.