简体   繁体   中英

Write and read from same file

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM