When I use a Try/Catch for open a file, the program display a inbuilt message instead of the one I have inside the Catch part, when I try to open a file that don’t exist. Whats wrong and what have I missed?
public void ReadFromFile(MainFrame obj, string filePath)
{
try
{
filestream = new FileStream(filePath, FileMode.Open);
BinaryFormatter b = new BinaryFormatter();
var animals2 = (List<Animal>)b.Deserialize(filestream);
foreach (Animal animal in animals2)
{
AddAnimalToList(animal);
obj.UppdateListOfRegistredAnimals(animal.ID, animal.Name, animal.Age, animal.Gender);
}
obj.UpdateId(animals.Count());
}
catch
{
MessageBox.Show("Test", "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
filestream.Close();
}
}
EDIT: I discovered that the reason for the inbuilt message is somewhere before the code above! Something must be wrong in the code below that handles an event from the openFileDialog, because despite several messageboxes, non is displayed! What have I done wrong!? Help is preciated!
private void menuFileOpen_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
string file = openFileDialog1.FileName;
if (result == DialogResult.OK)
{
MessageBox.Show("TEST", "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
try
{
MessageBox.Show("TEST", "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
motelManager.ReadFromFile(this, file); // Smart lösning!!
}
catch (FileNotFoundException)
{
MessageBox.Show("Error message", "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}

try this
for more info
http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
if you dont want the default message for file not found use