[英]CA2202 Do not dispose objects multiple times, How to Solve?
private string GetFileContent(string path)
{
if(File.Exists(HttpContext.Current.Server.MapPath(path)))
{
FileStream fs=null;
try
{
fs = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Open, FileAccess.Read);
using (TextReader tr = new StreamReader(fs))
{
fs.Flush();
return tr.ReadToEnd();
}
}
finally
{
fs.Close();
}
}
}
如果將FileStream fs分配給null,代碼將在沒有警告的情況下運行,但我不想將filestream分配為null,即在使用Statement時fs = null。
那么,不分配空值的正確寫法是什么?
擺脫try
/ finally
:
using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Open, FileAccess.Read))
using (TextReader tr = new StreamReader(fs))
{
fs.Flush();
return tr.ReadToEnd();
}
using
已經在做這樣的事情:
{
FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Open, FileAccess.Read);
try
{
// code inside the `using` goes here
}
finally
{
fs.Dispose();
}
}
從本質上講,處置遺囑可以關閉流程。
有關using
更多信息,請參見此問題 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.