0

My code is:

StreamReader r = new StreamReader("temp.txt");
string str = r.ReadLine();
Console.WriteLine(str);
StreamWriter w = new StreamWriter("temp.txt");
w.WriteLine("new text");
str = r.ReadLine();
Console.WriteLine(str);

When I run it, it throws an unhandled exception and cannot access the file. I’m sure the path of the file is correct and it is not write-protected.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • What is the exception? – RBarryYoung Aug 05 '21 at 16:38
  • 2
    StreamReader is IDisposable and locks your file. Just Dispose it or use "using" – ba-a-aton Aug 05 '21 at 16:40
  • Check the file [by code](https://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use) or with for example https://lockhunter.com/. See also @.HessamHosseini's and @.JoelCoehoorn answers. –  Aug 05 '21 at 16:43

2 Answers2

5

The file is locked because it's in use. It's not good to read and write to the same file at the same time. Wrap the streamreader/writers in using blocks, so the streams will be properly closed and released:

string str;
using (var r = new StreamReader("temp.txt"))
{
    str = r.ReadLine();
    Console.WriteLine(str);
}
using (var w = new StreamWriter("temp.txt"))
{
    w.WriteLine("new text");
}
using (var r = new StreamReader("temp.txt"))
{
    str = r.ReadLine();
    Console.WriteLine(str);
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
2

You can also use System.IO.File class when reading/writing over a file. The advantage here is that there is no need to open/close/dispose of streams, so the file will not be left in a locked state if you forget to dispose of your stream.

  //add this to namespace
using System.IO;

//read all lines from temp.txt and save to temptext variable
var tempText = File.ReadAllLines(@"C:\temp.txt");

//Add "new text" to the end of the text file and save it
File.AppendText(@"C:\temp.txt", "new text");
mason
  • 31,774
  • 10
  • 77
  • 121