You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#读取配置文件后,文件流Close()方法应放置在何处?

解决C#读取配置文件后关闭文件流的问题

首先得告诉你一个好消息:你当前的代码根本不需要手动调用Close()方法!

你用的File.ReadAllText()是.NET提供的静态工具方法,它的内部逻辑已经帮你完成了文件流的创建、读取和自动关闭/释放操作——方法执行完毕后,相关的文件资源会被自动清理,不会占用后续要使用的文件流资源。

不过可以给你的代码做个小优化,避免重复调用Split()(每次Split都会生成新的字符串数组,有点浪费性能):

string documentspath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string rpath = documentspath + @"\Luminous\remember.ini";
if (File.Exists(rpath)) {
    try {
        string text = File.ReadAllText(rpath);
        // 只Split一次,把结果存起来复用
        string[] configParts = text.Split('|');
        if (configParts.Length >= 3) { // 增加判断,避免数组越界
            string path = configParts[0];
            string process = configParts[1];
            string loadLib = configParts[2];
            
            pathBox.Text = path;
            processBox.Text = process;
            loadLibrary.Checked = loadLib == "True";
            manualMap.Checked = !loadLibrary.Checked;
        } else {
            MessageBox.Show("Config file corrupted. Remembered data has been lost and de...");
        }
    } catch {
        MessageBox.Show("Config file corrupted. Remembered data has been lost and de...");
    }
}

如果之后你需要手动操作文件流(比如用FileStream类),那时候才需要注意关闭流,最推荐的方式是用using语句,它会自动在代码块结束时释放资源(包括关闭流),示例:

using (FileStream fs = new FileStream(rpath, FileMode.Open))
{
    // 在这里进行文件流的读写操作
}
// 离开using块后,fs会被自动关闭和释放

内容的提问来源于stack exchange,提问作者biss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:17:59