File.ReadLines 读取文件后锁定文件,我无法写入

File.ReadLines keeps file locked after reading it and i can't write into it

出于某种原因 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();
    } 

那么你应该使用 StreamReader class 阅读所有行这样你的文件将被正确关闭我改变了你阅读行的方式以使用 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();
    } 

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