开发者

coding this function without memory leak! - please advise

In the following code example,will filestream and streamreader get disposed or will they create memory leaks? Is it possible to code this function without causing开发者_如何学Go memory leaks?

  string ReadFile(string strPath)
     {
         using (FileStream fstream = new FileStream(strPath, FileMode.Open))
         {
             using (StreamReader sreader = new StreamReader(fstream))
             {
                return sreader.ReadToEnd().ToString(); //NOTE ITS RETURNED HERE...SO CAN IT GET DISPOSED AFTER THIS LINE?
             }
         }
     }

Thanks


using directive means:

try
{
var iDisposable = new IDisposable();
//using iDisposable...
}
finally
{
//here IDisposable's dispose
}

So yes both fstream and sreader will be disposed.


The using directive calls the Dispose() method regardless whether the instantiating method returns within the block or not.

Please note, however, that you could use the System.IO.File.ReadAllText method to achieve the same with less code:

 string ReadFile(string strPath)
 {
     return System.IO.File.ReadAllText(strPath);
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜