I'm getting the following run time error: "I/O error while writing the file: "The process cannot access the file bin\Debug/test.txt because it is being used by another process."
I have closed the files in all cases it's being written, except the case when File.ReadAllText(path) is used as my understanding is that the filestream is closed automatically. How do I correct this error?
Here is the relevant code:
 StreamReader sr = null;
 sr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
 try
 {
     // Open the file for reading; assumes file exists
     sr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
     while (!sr.EndOfStream)
     {
         line = sr.ReadLine();
         fields = line.Split(',');
         aniNameCol1[count] = fields[0];
         aniNameCol2[count] = fields[1];
         aniNameCol3[count] = fields[2];
         aniNameCol4[count] = fields[3];
         count++;
     }
     sr.Close();
     sr.Dispose();
}
catch (FileNotFoundException)
{
    MessageBox.Show("File Not Found" + path);
}
catch (Exception ex)
{
    MessageBox.Show("Error while reading the file: " + ex.GetType().ToString() + ": " + ex.Message);
}
finally
{
    if (sr != null)
    {
        sr.Close();
        sr.Dispose();
    }                                          
}
try
{
     string input = File.ReadAllText(path);
     int i = 0;
     int j = 0;
     foreach (var row in input.Split('\n'))                  
     {
         j = 0;
         foreach (var col in row.Trim().Split(','))
         {
             twoDArray[i, j] = col.Trim().ToString();
             j++;
         }
         i++;
     }
 }
 catch (FileNotFoundException)
 {
     MessageBox.Show("File Not Found" + path);
 }
 catch (Exception ex)
 {
     MessageBox.Show("Error while reading the file: " + ex.GetType().ToString() + ": " + ex.Message);
 }
In another method, text is written in the file:
 StreamWriter sw = null;
 try
 {
     // open the same file for writing            
     sw = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write));
     for(int i = 0; i < rowMax; i++)
     {
         for(int j = 0; j < colMax; j++)
         {
             sw.WriteLine(twoDArray[i, j].ToString() + ", ");
         }
     }
     sw.Close();
     sw.Dispose();
  }
  catch (IOException ex)
  {
    MessageBox.Show("I/O error while writing the file: " + ex.Message);
  }
  catch (Exception ex)
  {
    MessageBox.Show("Unanticipated error occurred while writing: " + ex.GetType() + "; " + ex.Message);
   }   
   finally
   {
       if (sw != null)
       {
          sw.Close();
          sw.Dispose();
       }           
   }
 
     
     
    