Friday, 17 June 2011

Work Musings - Open File Dialog

The other day while working on the open file dialog control in c#, it dawned to us that the openfiledilalog remembers the path of the previous file. This can introduce subtle errors. As an example let us assume that we have an app that writes a line of text to a file such as say a disclaimer.



private void button1_Click(object sender, EventArgs e)
{
String fileName = String.Empty;
DialogResult dlg = openFileDialog1.ShowDialog();
fileName = openFileDialog1.FileName;
if (String.IsNullOrEmpty(fileName) == false)
{
StreamWriter wrt = new StreamWriter(fileName, true);
wrt.WriteLine("So lets see this is my impact ");
wrt.Close();

}

}

IF the user were to open a file for the first time and write the disclaimer to it and
then decides to open a second file in the open file dialog and presses cancel , the
openfile dialog will still remember the previous file name and cause the text to be written again.


To over come this , this piece of code will be apt :
private void button1_Click(object sender, EventArgs e)
{
String fileName = String.Empty;
//Note how the file Name is initialized
`````````` DialogResult dlg = openFileDialog1.ShowDialog();
switch (dlg)
{
case DialogResult.OK:
fileName = openFileDialog1.FileName;
break;
default:
fileName = String.Empty;
break;

}

if (String.IsNullOrEmpty(fileName) == false)
{
StreamWriter wrt = new StreamWriter(fileName, true);
wrt.WriteLine("So lets see this is my impact ");
wrt.Close();

}

}

No comments:

Post a Comment