filelockingstreamwriterfile.readalllines

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


For some reason File.ReadLines keeps the file that im reading locked, and when i am trying to write text into it using a streamWriter, i get an error that it is being used by another process. If i don't read it first, writing into it works fine. Here is my code:

    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();
    } 

Solution

  • Well you should read all the lines using StreamReader class that way your file will be properly closed I altered the way you are reading lines to read all lines using StreamReader try the following version

        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();
        } 
    

    I have not tested the code but I am sure it will solve your problem