[英]Visual C# When are Close() and Dispose() Needed?
我是 Visual C# 的新手,不明白何时需要对 FileStream 和 StreamReader 对象使用 Close() 和 Dispose() 方法。 在下面的代码片段中,我打开一个文件,读取第一行,并验证它是否符合预期。 我需要显示所有的 Close() 和 Dispose() 调用吗? 如果没有,什么时候需要它们? 谢谢!
FileStream fs = null;
StreamReader sr = null;
try
{
fs = new FileStream(txtMstrFile.Text, FileMode.Open, FileAccess.Read);
using (sr = new StreamReader(fs))
{
if (String.IsNullOrEmpty(sLine = sr.ReadLine()))
{
MessageBox.Show(Path.GetFileName(txtMstrFile.Text) + " is an empty file.", "Empty Master File", MessageBoxButtons.OK,
MessageBoxIcon.Information);
sr.Close();
fs.Close();
fs.Dispose();
return;
}
if(!String.Equals(sLine, "Master File"))
{
MessageBox.Show(Path.GetFileName(txtMstrFile.Text) + " has an invalid format.", "Master File is Invalid", MessageBoxButtons.OK,
MessageBoxIcon.Error);
sr.Close();
fs.Close();
fs.Dispose();
return;
}
// Code to process sLine here
sr.Close();
}
fs.Close();
fs.Dispose();
}
catch (IOException ex)
{
MessageBox.Show(Path.GetFileName(txtMstrFile.Text) + "\r\n" + ex.ToString(), "File Access Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
sr.Close();
fs.Close();
fs.Dispose();
return;
}
sr.Close();
fs.Close();
fs.Dispose();
显式Dispose()
和Close()
是典型代码中的罕见建议: using
将为您完成:
try {
using (var sr = new StreamReader(new FileStream(txtMstrFile.Text,
FileMode.Open,
FileAccess.Read))) {
string sLine = sr.ReadLine();
if (String.IsNullOrEmpty(sLine)) {
MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)} is an empty file.",
"Empty Master File",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
if (!String.Equals(sLine, "Master File")) {
MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)} has an invalid format.",
"Empty Master File",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
}
}
catch (IOException ex) {
MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)}\r\n{ex}",
"File Access Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
请不要在创建消息时连接字符串,字符串插值: $"... "
通常更具可读性。
编辑:您可以完全摆脱Stream
和StreamReader
:
try {
// That's enough to read the 1st file's line
string sLine = File.ReadLines(txtMstrFile.Text).First();
if (String.IsNullOrEmpty(sLine)) {
MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)} is an empty file.",
"Empty Master File",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
if (!String.Equals(sLine, "Master File")) {
MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)} has an invalid format.",
"Empty Master File",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
}
catch (IOException ex) {
MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)}\r\n{ex}",
"File Access Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
一些计算机语言将 memory 管理留给程序员,因此释放不再需要的 memory 称为垃圾回收。 Dispose 是程序员说“立即清理”的方式。 Close 用于关闭诸如与数据库的连接之类的东西。 关闭表示“现在将任何未写入的数据写入文件”,这是一种安全措施,可确保在计算机崩溃时保存文件数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.