从同一个文件写入和读取

Write and read from same file

我一直在考虑将一个字符串写入一个文件,然后逐行读取它,但我总是收到错误 IOException: Sharing violation on path C:...\level1.txt。我在网上看了看,他们说我应该使用相同的流来写入和读取,但是没有用,所以我尝试为每个流创建不同的流,但也没有用。

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

我认为你只需要使用 Using statementread and write.

由于StreamWriterStreamReader 类继承了Stream,它实现了IDisposable接口,示例可以使用using语句来确保底层文件在写入或读取操作后正确关闭。

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.