1

I have been looking at writing a string into a file and then read it line by line, but I always get the error IOException: Sharing violation on path C:...\level1.txt. I looked on the internet and they said I should use the same stream to write and read but it didn't work,so I tried to make a different stream for each one and it didn't work either.

FileStream F = new FileStream("level1.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
        StreamWriter sw = new StreamWriter(F);
        sw.Write(Gui.codeText.Replace("\n", "\r\n"));
        F.Close();
 FileStream F2 = new FileStream("level1.txt", FileMode.Open, FileAccess.Read);
        StreamReader file = new StreamReader(F2);
        while ((line = file.ReadLine()) != null)
        { ....}
Irshad
  • 2,860
  • 5
  • 25
  • 45
Chimo
  • 13
  • 2
  • try this http://stackoverflow.com/questions/605685/how-to-both-read-and-write-a-file-in-c-sharp – Irshad Oct 22 '15 at 04:36
  • that's what I was looking at, I tried the same thing but with FileStream F = new FileStream("level1.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(F); StreamReader file = new StreamReader(F); and I still got the same error – Chimo Oct 22 '15 at 04:46

1 Answers1

0

I think you just need to use the Using statement while read and write.

Since the StreamWriter and StreamReader classes inherits Stream, which is implements the IDisposable interface, the example can use using statements to ensure that the underlying file is properly closed following the write or read operations.

using (StreamWriter sw = new StreamWriter(F))
{
      //Write Logic goes here...
}

using (StreamReader file = new StreamReader(F2))
{
     //Read Logc goes here...
}

The Using Statement:

An using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.

RajeshKdev
  • 6,029
  • 6
  • 53
  • 76