【问题标题】:Understanding where cursor position of a file is stored and modified了解文件的光标位置存储和修改的位置
【发布时间】:2019-12-09 07:39:01
【问题描述】:

在使用流写入或读取文件时,我无法理解光标位置是谁以及如何保留的。

我有以下情况:

-Get a `stream`
-Write said `stream` to file
-Create a new stream and read said file
-This stream position is at end

为什么新创建的流的位置在末尾?

class Program
    {
        public static async Task WriteAsync(Stream inboundStream,string path)
        {
            using FileStream fstream = new FileStream(path, FileMode.Create, FileAccess.Write);
            await inboundStream.CopyToAsync(fstream);

        }
        public static async Task<Stream> ReadAsync(string path)
        {
            MemoryStream memstream = new MemoryStream();
            using FileStream fstream = new FileStream(path, FileMode.Open, FileAccess.Read);
            await fstream.CopyToAsync(memstream);
            return memstream;
        }
        static async Task Main(string[] args)
        {
            string path = "hello.txt";
            using (MemoryStream memstream = new MemoryStream(Encoding.UTF8.GetBytes("hello hey")))
            {
                await WriteAsync(memstream, path);
            }
            using Stream readStream = await ReadAsync(path); //why is the position of this guy at the end ?
        }
    }

我不明白,当我写入文件时,光标的位置是否嵌入其中或光标位置存储在哪里?如果没有这样的位置以某种方式存储,那么一个新的Stream 读取资源应该从头开始。

【问题讨论】:

  • 流中没有游标。当你写到末尾时,位置就是流的末尾。当你读到最后时,位置在流的末尾,因为这就是你所做的 - 你读到了流的末尾

标签: c# .net stream


【解决方案1】:

从一个流读取并写入另一个流后,另一个流在其末尾,因为您刚刚将其写入末尾。

特别是这一行:

await fstream.CopyToAsync(memstream);

memstream 现在将位于末尾,因为它刚刚写入了另一个流。

您需要使用Seek 重新开始。在上面一行之后:

memstream.Seek(0, SeekOrigin.Begin);

【讨论】:

  • 而不是复制你的答案,我会编辑你的。如果您觉得我过度编辑您的答案,请随时回复我。
  • 我正在使用不同的FIleStreams 来读取和写入文件,如您所见!我知道我必须使用Seek,如果我将使用相同的FileStream 进行阅读和写作。那不是我的情况!
  • @BercoviciAdrian 怎么不是这样?当您写入流时,位置指向流的末端。如果您将流读到其末尾,则该位置是流的末尾。不管是什么流,如果你想回到起点,你需要 Seek。
  • 但我正在使用FileStream 写入文件,我们称之为fs1。我将使用fs2 从文件中读取。当您说stream's end 时,我们在谈论哪一端? Fs1 在我读取文件时不再使用。
  • @BercoviciAdrian 抱歉没有早点注意到这些 cmets。最后是memstream,而不是文件流。 fstream.CopyToAsync 在最后留下memstream(这是有道理的,因为如果你要写更多,它应该在最后继续写。)为了从头开始阅读memstream,你需要“倒带”首先。
猜你喜欢
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 2015-05-25
相关资源
最近更新 更多