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

VB.NET:读取文本文件后如何正确释放以便同一程序中写入?

彻底释放文件资源的解决方法

在VB.NET中,最可靠的方式是使用Using语句自动管理文件流资源,它能确保无论代码执行是否正常,都会自动释放文件句柄,避免资源泄漏导致的文件占用问题。

修改读取代码

替换原有读取逻辑为Using块,无需手动调用Close()、Dispose()或设置变量为Nothing:

If File.Exists(outfile) Then
    ' Load existing CSV file into csvFIle string to be used a check for duplicates
    Using rdr As New StreamReader(outfile)
        csvFile = rdr.ReadToEnd
    End Using
End If

修改写入代码

同样用Using块包裹StreamWriter,确保写入完成后立即释放资源:

Using sw As New StreamWriter(outfile, True) ' append to file
    If newFL Then   ' if the file is new then write the HEADER to the file
        If outbuff <> "" Then sw.WriteLine(outbuff)
        outbuff = ""
        newFL = False
    End If
    ' 此处添加其他写入逻辑
End Using

原理说明

Using语句会在代码块结束时自动调用对象的Dispose()方法,强制释放文件占用的系统资源(包括文件句柄)。相比手动调用释放方法,它能处理异常场景——即使读取或写入过程中抛出错误,资源也会被正确释放,从根本上避免“文件正被另一进程使用”的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:14:55