【问题标题】:How to read and write simultaneously from same file in C#如何在C#中同时从同一个文件中读取和写入
【发布时间】:2012-08-31 03:47:56
【问题描述】:

我想将数据写入文件并读取它以在 C# 中同时显示。 如何做到这一点?

【问题讨论】:

    标签: c# file filestream streamwriter operation


    【解决方案1】:
    var fs = new System.IO.FileStream(fileName, System.IO.FileAccess.ReadWrite);
    

    然后你就可以打电话了

     long oldPos = fs.Position;
     fs.Write(....);
     fs.Flush();
     fs.Position = oldPos;
     fs.Read(...);
    

    【讨论】:

      【解决方案2】:

      写入后刷新,然后读取。

      对了,为什么不凭记忆显示呢?

      【讨论】:

        【解决方案3】:

        您可以打开一个 FileStream 进行读取和写入。例如:

        byte[] writeBuffer; // Contains data to write
        byte[] readBuffer;  // Large enough space to read data
        FileStream fileStream = new FileStream("file.txt", 
            FileMode.OpenOrCreate, FileAccess.ReadAndWrite);
        fileStream.Write(writeBuffer, 0, writeBuffer.Length);
        fileStream.Seek(0, SeekOrigin.Begin);
        fileStream.Read(readBuffer, 0, readBuffer.Length);
        

        您可以使用同一个对象进行读取和写入。但是,同时执行这两项操作需要在您的应用程序中进行仔细协调,以防止操作相互干扰。更好的解决方案可能是将操作排队。

        【讨论】:

          猜你喜欢
          • 2010-10-10
          • 1970-01-01
          • 2018-11-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多