Ajay AJ (Community Member) asked a question.

CWE 404 - Improper Resource Shutdown or Release

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();

        }


  • Robert (Community Member)

    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.

    Expand Post
    • Tom at Viewpointe (Community Member)

      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

Topics (4)

No articles found
Loading

Ask the Community

Get answers, share a use case, discuss your favorite features, or get input from the community.