Tuesday, July 7, 2015

Closing stream after error

Sometimes there are cases where it is appropriate to create one streamReader to be used with multiple files like the code below. But what if an error were to occur before the stream closed. Uh oh, theres a problem. Our catch would catch the exception, but we would get an error when an attept is made to move the file to the Error directory. What do we do?
Easy, wrap your stream in a using statement and remove the "stream.Close()" because it's no longer needed. This will make sure the stream is closed even if there is an exception during the Parsing of the XML.
The file can be moved successfully and you will not have to worry about memory leaks.

StreamReader stream;
DirectoryInfo ImportDir = new DirectoryInfo(importFileDirectory);
var Files = Directory.GetFiles(importFileDirectory, "*.dat").Select(fn => new FileInfo(fn)).OrderBy(f => f.Name);
foreach (FileInfo file in Files)
{
if (checkFileAvailable(file.FullName))
{
try
{
BatchID = file.Name.Remove(file.Name.Length - 4);
xmldoc.Load(stream);
ParseXML(xmldoc);

stream.Close();

//move file to archive folder
DateTime dt = DateTime.Now;
string s = dt.ToString("yyMMddHHmmss");
System.IO.File.Move(file.FullName, archiveFileDirectory + file.Name.Remove(file.Name.Length - 4) + s + file.Extension);

}
catch (Exception ex)
{
//move file to Error folder
DateTime dt = DateTime.Now;
string s = dt.ToString("yyMMddHHmmss");
System.IO.File.Move(file.FullName, errorFileDirectory + file.Name.Remove(file.Name.Length - 4) + s + file.Extension);

LogDescription = string.Format("Import ERROR!");
Logger.Log_Err(LogDescription, ex);
Logger.LogDistributionResult("0", "0", "0", "C4", "F", "IN", BatchID, "File Failed to Load: Exception: " + ex);
continue;
}
}
}

This is the way the new code will look inside the try.

//Use a using to make sure a stream is closed even if there is an exception.
using (stream = new StreamReader(file.FullName))
{
BatchID = file.Name.Remove(file.Name.Length - 4);
xmldoc.Load(stream);
ParseXML(xmldoc);
}
//move file to archive folder
DateTime dt = DateTime.Now;
string s = dt.ToString("yyMMddHHmmss");
System.IO.File.Move(file.FullName, archiveFileDirectory + file.Name.Remove(file.Name.Length - 4) + s + file.Extension);

No comments:

Post a Comment