
Ajay AJ (Community Member) asked a question.
What is wrong in this code?
FileInfo fileInfo = new FileInfo(sPath);
if (fileInfo.Exists)
{
FileStream fs = new FileStream(sPath, FileMode.Append, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs);
writer.Write("\r\n \r\n \r\n " + sText);
writer.Close();
fs.Close();
}
else
{
FileStream fs = new FileStream(sPath, FileMode.CreateNew, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs);
writer.Write(sText);
writer.Close();
fs.Close();
}
.png)
If an exception is thrown, the StreamWriter and FileStream won't be closed. They should be in a try-with-resources statement as follows:
try (FileStream fs = new FileStream(sPath, FileMode.CreateNew, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs)) {
writer.Write(sText);
}
(It's also a lot simpler to read as you don't explicitly need the close())
See documentation on the AutoClosable interface.
We're seeing the same problem - CWE 404s are being flagged on a couple try-with-resource using JDK 1.8. I saw another post that suggested including debug symbols for the build. Will this give Veracode enough information to NOT flag this flaw? Or will I have to mitigate it? TIA