码:

        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");


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

最佳答案

您应该在StreamReader语句中关闭StreamWriterusing,如下所示:

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/

10-10 13:08