该进程无法访问该文件,因为该文件正由另一个进程使用。 (文本文件不会关闭)

时间:2014-07-07 20:54:30

标签: c# .net streamreader streamwriter

我尝试在此代码块检查上次重启PC后写入文本文件。下面的代码从文本文件中读取,上次重新启动PC时,从那里确定是否显示启动画面。但是,运行此方法后,我需要向文本文件写入当前“System Up-Time”的内容。但我一直收到错误,说明文本文件正在使用中。这让我疯了。我已确保所有StreamWriters和StreamReader都已关闭。我尝试过使用语句。我试过GC.Collect。我觉得我已经尝试了一切。

任何帮助都将不胜感激。

    private void checkLastResart()
    {
        StreamReader sr = new StreamReader(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt");
        if (sr.ReadLine() == null)
        {
            sr.Close();
            MessageBox.Show("There was an error loading 'System UpTime'. All settings have been restored to default.");
            StreamWriter sw = new StreamWriter(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt", false);
            sw.WriteLine("Conversion Complete Checkbox: 0");
            sw.WriteLine("Default Tool: 0");
            sw.WriteLine("TimeSinceResart: 0");
            sw.Flush();
            sw.Close();
        }
        else
        {
            try
            {
                StreamReader sr2 = new StreamReader(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt");
                while (!sr2.EndOfStream)
                {
                    string strSetting = sr2.ReadLine();
                    if (strSetting.Contains("TimeSinceResart:"))
                    {
                        double lastTimeRecorded = double.Parse(strSetting.Substring(17));

                        //If the lastTimeRecorded is greater than timeSinceResart (computer has been resarted) OR 2 hours have passed since LVT was last run
                        if (lastTimeRecorded > timeSinceRestart || lastTimeRecorded + 7200 < timeSinceRestart)
                        {
                            runSplashScreen = true;
                        }
                        else
                        {
                            runSplashScreen = false;
                        }
                    }
                }
                sr2.Close();
                sr2.Dispose();
            }
            catch (Exception e) { MessageBox.Show("An error has occured loading 'System UpTime'.\r\n\r\n" + e); }
        }
    }               

以下是在运行上述代码后写入文本文件的示例。无论我打开StreamWriter,还是使用File.WriteAllLines,都会立即抛出错误。

StreamWriter sw = new StreamWriter(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt");
            string[] lines = File.ReadAllLines(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt");
            lines[2] = "TimeSinceResart: " + timeSinceRestart;
            foreach (string s in lines)
                sw.WriteLine(s);

2 个答案:

答案 0 :(得分:2)

您的编写代码应以这种方式更改

string file = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"Settings.txt");

// First read the two lines in memory
string[] lines = File.ReadAllLines(file);

// then use the StreamWriter that locks the file
using(StreamWriter sw = new StreamWriter(file))
{
     lines[2] = "TimeSinceResart: " + timeSinceRestart;
     foreach (string s in lines)
         sw.WriteLine(s);
}

通过这种方式,StreamWriter上的锁定不会阻止使用FileReadAllLines读取。
说,请注意几件事。不要使用字符串连接创建路径字符串,请使用Path类的静态方法。但最重要的是,当您创建像流一样的一次性对象时,请务必使用using statement正确关闭文件

完成答案以回应您的评论。也使用语句代码的第一部分

private void checkLastResart()
{
    string file = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"Settings.txt");
    using(StreamReader sr = new StreamReader(file))
    {
        if (sr.ReadLine() == null)
        {
            sr.Close();
            MessageBox.Show(...)
            using(StreamWriter sw = new StreamWriter(file, false))
            {
                sw.WriteLine("Conversion Complete Checkbox: 0");
                sw.WriteLine("Default Tool: 0");
                sw.WriteLine("TimeSinceResart: 0");
                sw.Flush();
            }
        }
        else
        {
            ....
        }
    } // exit using block closes and disposes the stream
}

答案 1 :(得分:0)

在您创建sr2的位置,sr仍然打开settings.txt。