在使用流写入或读取文件时,我很难理解谁以及如何保留光标位置。
我有以下情况:
-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
会读取资源应该从头开始。
从一个流中读取并写入另一个流之后,另一流在其末尾,因为您只是将其写入末尾。
特别是这行:
await fstream.CopyToAsync(memstream);
[memstream
现在将在最后,因为它刚刚写入了另一个流。
您需要使用Seek
重新开始。就在以上行之后:
memstream.Seek(0, SeekOrigin.Begin);