我是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) + "rn" + 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)}rn{ex}",
"File Access Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
请不要在创建消息时连接字符串,字符串插值:$" ... "
通常更具可读性。
编辑:您可以完全摆脱Stream
s和StreamReader
s:
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)}rn{ex}",
"File Access Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
一些计算机语言将内存管理留给程序员,因此释放不再需要的内存被称为垃圾收集。Dispose是程序员说";立即清理";。Close用于关闭与数据库的连接。克洛斯说";立即将任何未写入的数据写入文件";并且是一种安全措施,可以确保在计算机崩溃时保存您的文件数据。