c# - Visual C# When are Close() and Dispose() Needed?
问题描述
I am new to Visual C# and don't understand when I need to use the Close() and Dispose() methods on FileStream and StreamReader objects. In the code snippet below, I open a file, read the first line, and validate that it is what is expected. Do I need all of the Close() and Dispose() calls shown? If not, when are they needed? Thank you!
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
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)}\r\n{ex}",
"File Access Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
推荐阅读
- oauth-2.0 - 解释 Open ID 连接中的离线令牌验证与在线令牌验证?优势、局限和权衡
- php - Nginx + Php-fpm fastcgi 上游超时
- node.js - React 应用程序无法加载 localhost:3000
- visual-studio - 无法从 VS2017 加载模板到 VS2019
- python - Python Scrapy Crawler - 尝试在 Github 上自动记录问题不起作用 - Gist 无法在 Linux 机器上创建(适用于 Windows)
- qt - 将 CMake 项目导入现有 QT 项目 .pro
- postgresql - Spring Batch - 多步执行模型,如果第 3 步失败,则第 1 步和第 2 步插入的数据也应该回滚
- apache-flink - Apache Flink 中的不可序列化对象
- java - Apache POI 获取字体指标
- javascript - 来自 puppeteer 文档的代码在 UnhandledPromiseRejectionWarning 之前不起作用