File Opening
I've decided to work on the opening of a file. I've created an OpenFileDialog (and a SaveFileDialog for later) to open a .tl file, which is the extension I'll use to set it up. My dialog box looks something like this:
this.ofdDialog.DefaultExt = "tl";
this.ofdDialog.Filter = "Task Lists(*.tl)|*.tl";
this.ofdDialog.Title = "Open Task List";
this.ofdDialog.InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
From previous experience of an application using multiple file dialogs, I created two methods:
private string GetFileFromDialog(FileDialog dialog)
{
if (dialog.ShowDialog() == DialogResult.OK)
{
this.SaveDirectory(dialog, dialog.FileName);
return dialog.FileName;
}
return string.Empty;
}
private void SaveDirectory(FileDialog dialog, string filePath)
{
FileInfo info = new FileInfo(filePath);
dialog.InitialDirectory = info.DirectoryName;
}
When opening a file and navigating to a folder, I wanted to save the directory navigated to, at least for the application session. So I created the SaveDirectory method to save the directory of a file to the dialog box, overwriting the MyDocuments default option. I use the FileInfo as a convenient way to get the directory path.
GetFileFromDialog makes the action of retrieving the file name unique and avoids duplicating code for opening and saving files, which is a good refactoring to do. I knew of this ahead of time from past experience with applications, and so I have this method return the selected file name, or empty if nothing.
For the opening of the file, I have a menu. This menu is defined as this:
private void msiFileOpen_Click(object sender, EventArgs e)
{
string file = this.GetFileFromDialog(this.ofdDialog);
StreamReader reader = new StreamReader(file);
string xml = reader.ReadToEnd();
if (!string.IsNullOrEmpty(xml))
{
}
else
MessageBox.Show("The file you selected is not a valid task file");
}
I get the file, open it and get the XML. I want to ensure the file actually does have XML, and so I test it. In the first part of the if statement, I am going to use my MetadataSerialization object I created. Unfortunately, I found a problem.