0

出于某种原因,File.ReadLines 使我正在读取的文件保持锁定状态,并且当我尝试使用 streamWriter 将文本写入其中时,我收到一个错误,表明它正在被另一个进程使用。如果我不先阅读它,写入它就可以了。这是我的代码:

    IEnumerable<String> lines;
    private void loadCfg()
    {
        lines = File.ReadLines(Application.StartupPath + @"\server.cfg");
        foreach (var line in lines)
        {
            if (line.Contains("Port"))
            {
                portTxtBox.Text = extractValue(line);
            }
            if (line.Contains("Cars"))
            {
                maxCarsCombo.Text = extractValue(line);
            }
            if (line.Contains("MaxPlayers"))
            {
                maxPlayerCombo.Text = extractValue(line);
            }
         }
      }

   private void saveBtn_Click(object sender, EventArgs e)
    {
        StreamWriter sw = new StreamWriter(Application.StartupPath + @"\server.cfg",false);
        sw.WriteLine(lines.ElementAt(0));
        sw.Close();
    } 
4

1 回答 1

1

好吧,您应该使用StreamReader类读取所有行,这样您的文件将正确关闭我更改了您读取行的方式以使用StreamReader尝试以下版本读取所有行

    List<string> lines = new List<string>()
    private void loadCfg()
    {
        string temp = null;
        StreamReader rd = new StreamReader(Application.StartupPath + @"\server.cfg");
        temp = rd.ReadLine();
        while(temp != null)
        {
            lines.Add(temp);
            temp = rd.ReadLine();
        }
        rd.Close();

        foreach (var line in lines)
        {
            if (line.Contains("Port"))
            {
                portTxtBox.Text = extractValue(line);
            }
            if (line.Contains("Cars"))
            {
                maxCarsCombo.Text = extractValue(line);
            }
            if (line.Contains("MaxPlayers"))
            {
                maxPlayerCombo.Text = extractValue(line);
            }
         }
    }

   private void saveBtn_Click(object sender, EventArgs e)
    {
        StreamWriter sw = new StreamWriter(Application.StartupPath + @"\server.cfg",false);
        sw.WriteLine(lines.ElementAt(0));
        sw.Close();
    } 

我还没有测试过代码,但我相信它会解决你的问题

于 2021-06-23T12:29:41.340 回答