I have a couple questions on how to do file handling properly. I use binary serialization and deserialization in my program. On top of that I also export and import text files. I listed a example below of my serialization code. I use an openfile dialog to select folders/files.
This is my binary serialization method:
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentOutOfRangeException("fileName");
}
FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate);
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream, Animals);
}
finally
{
fileStream.Close();
}
And these are the exceptions i catch:
try
{
administration.Load(fileName);
}
catch (NotSupportedException nonSupportedException)
{
MessageBox.Show(nonSupportedException.Message);
}
catch (UnauthorizedAccessException unauthorizedAccesException)
{
MessageBox.Show(unauthorizedAccesException.Message);
{
catch (SecurityException securityException)
{
MessageBox.Show(securityException.Message);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
MessageBox.Show(directoryNotFoundException.Message);
}
catch (IOException IOException)
{
MessageBox.Show(IOException.Message);
}
I catch the same exceptions for deserialization. The only difference there is these 3 lines:
if (File.Exists(fileName)) { }
FileStream fileStream = new FileStream(fileName, FileMode.Open);
Animals = formatter.Deserialize(fileStream) as List<Animal>;
What should I do if I get wrong data? For example: half of the file has the right data and the other half doesn't.
How should i write unit tests for serialization? Many exceptions like SecurityException are hard to test.
What exceptions should I catch? I looked at MSDN, but I am not sure if I should just straight up catch all of the exceptions listed. I deliberately don't catch the ArgumentOutOfRange exception for example, because I don't want to catch programming mistakes.
I have the same questions for reading and writing text files. Is there a difference in testing/exception catching? The only difference is that I use StreamWriter for writing text files. And I use File.ReadAllLines to read the text file I select.
Thank you.