【发布时间】: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 读取资源应该从头开始。
【问题讨论】:
-
流中没有游标。当你写到末尾时,位置就是流的末尾。当你读到最后时,位置在流的末尾,因为这就是你所做的 - 你读到了流的末尾