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)
{ ....}
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...
}
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.