0

I am using a filestream and streamwriter to write a small text on file it giving me CA2202 warning

    public void WritePIDToFile()
    {
        FileStream fh = null;
        try
        {
            fh = new FileStream(HIMSHelper.ApplicationDirectory + "PID", FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
            using (var sr = new StreamWriter(fh))
            {
                sr.Write(PID);
            }
        }
        finally
        {
            if (fh != null)
            {
                fh.Dispose();//I got CA2202 here
            }
        }
    }

I already try the solution here CA2202: Do not dispose objects multiple times

Can you give me any suggestions? Please.

Thanks

zer09
  • 1,507
  • 2
  • 28
  • 48
  • Your `using` block will close the `StreamWriter`, and that may be closing the `FileStream` object as well. Even if the code errors out in the `using` block, the object(s) will still be closed and disposed. – Tim Jan 24 '16 at 07:53
  • "I already try the solution here" -- Not exactly: the `fh = null;` line is missing in your code. –  Jan 24 '16 at 07:56
  • yeah setting fh = null before calling sr.Write() solve the problem, but i am little worried that it could give an inconsistent behavior. does it? – zer09 Jan 24 '16 at 07:58
  • What possible inconsistencies are you thinking about? I ask because I'm not seeing it. –  Jan 24 '16 at 08:01
  • Is it ok to set the fh = null before calling sr.Write(PID)? – zer09 Jan 24 '16 at 08:05
  • Yes, that's okay. `sr.Write(PID)` doesn't look at the current value of the `fh` variable. It can't, it has no access to it. You passed in the old value with `var sr = new StreamWriter(fh)`, and that old value will be used by `sr.Write(PID)`. –  Jan 24 '16 at 08:10
  • Thank you very much, thats a great help. – zer09 Jan 24 '16 at 08:14

0 Answers0