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, т. е. 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
.
Проверьте комментарии к ответу Джона Скита на этот вопрос.