c# - 在 c# 中使用 file.move 时文件锁定...如何停止或修复此问题

标签 c# file filelock

代码:

        String tempFile = Path.GetTempFileName(), read = "";
        TextReader pending = new StreamReader("c:\\pending.txt");
        TextWriter temp = new StreamWriter(tempFile);

        read = pending.ReadLine();

        while ((read = pending.ReadLine()) != null)
        {
            temp.WriteLine(read);
        }

        pending.Close();
        temp.Close();

        File.Delete("c:\\pending.txt");
        File.Move(tempFile, "c:\\pending.txt");

pending.txt 文件如果不存在则在程序启动时创建。此代码删除文件的第一行。当我调试代码时,我注意到

        File.Move(tempFile, "c:\\pending.txt");

锁定文件,我不能再写入了。

最佳答案

您应该在 using 语句中关闭您的 StreamReaderStreamWriter,如下所示:

String tempFile = Path.GetTempFileName(), read = "";
using(TextReader pending = new StreamReader("c:\\pending.txt"))
using(TextWriter temp = new StreamWriter(tempFile))
{

    read = pending.ReadLine();

    while ((read = pending.ReadLine()) != null)
    {
        temp.WriteLine(read);
    }
}

File.Delete(@"c:\pending.txt");
File.Move(tempFile, @"c:\pending.txt");

关于c# - 在 c# 中使用 file.move 时文件锁定...如何停止或修复此问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2339383/

相关文章:

java - 如何锁定其他线程的文件

c# - 在 MVC Razor 中访问 WCF 服务

c# - DDD(Domain Driven Design),如何处理实体状态变化,封装需要处理大量数据的业务规则

jquery - 如何将 jQuery 插件拆分为多个文件

c++ - boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为

c# - 删除由 vshost.exe c# 锁定的图像文件

c# - 针对接口(interface)编程而不是实现混淆

c# - 如何点击另一个按钮上方的按钮?

c++ - 'ifstream' 的初始化没有匹配的构造函数

file - 如何通过终端(bash shell)快速删除文件和目录