T
tshad
Do I still need to close an object in a finally statement after a catch if
it is part of a using statement?
For example:
FileStream fs = null;
try
{
using (FileInfo fInfo = new FileInfo(fromImagePath + "\\" +
(string)dr["originalFileName"]))
{
if (fInfo.Exists)
{
numBytes = fInfo.Length;
// Read the file into the byte array
using (fs = new FileStream(fromImagePath + "\\" +
(string)dr["originalFileName"], FileMode.Open, System.IO.FileAccess.Read))
{
using(BinaryReader br = new BinaryReader(fs))
myByteArray = br.ReadBytes((int)numBytes);
}
// Write out the file into the images folder with new name
using (fs = System.IO.File.OpenWrite(imagePath + imageName))
{
fs.Write(myByteArray, 0, myByteArray.Length);
}
}
}
}
catch (Exception exc)
{
}
finally
{
if (br != null)
br.Close();
if (fs != null)
fs.Close();
}
Do I need to use the finally code or does the "using" automatically close
the objects (fs and br)?
Also, when the you exit the using statement (with or without an error -
which would send you to the catch clause), would the an object that was
defined outside of the using statement be null?
Thanks,
Tom
it is part of a using statement?
For example:
FileStream fs = null;
try
{
using (FileInfo fInfo = new FileInfo(fromImagePath + "\\" +
(string)dr["originalFileName"]))
{
if (fInfo.Exists)
{
numBytes = fInfo.Length;
// Read the file into the byte array
using (fs = new FileStream(fromImagePath + "\\" +
(string)dr["originalFileName"], FileMode.Open, System.IO.FileAccess.Read))
{
using(BinaryReader br = new BinaryReader(fs))
myByteArray = br.ReadBytes((int)numBytes);
}
// Write out the file into the images folder with new name
using (fs = System.IO.File.OpenWrite(imagePath + imageName))
{
fs.Write(myByteArray, 0, myByteArray.Length);
}
}
}
}
catch (Exception exc)
{
}
finally
{
if (br != null)
br.Close();
if (fs != null)
fs.Close();
}
Do I need to use the finally code or does the "using" automatically close
the objects (fs and br)?
Also, when the you exit the using statement (with or without an error -
which would send you to the catch clause), would the an object that was
defined outside of the using statement be null?
Thanks,
Tom