gpt4 book ai didi

c# - 在 C# 中将 Stream 转换为 FileStream

转载 作者:可可西里 更新时间:2023-11-01 08:06:21 27 4
gpt4 key购买 nike

使用 C# 将 Stream 转换为 FileStream 的最佳方法是什么。

我正在处理的函数有一个包含上传数据的 Stream 传递给它,我需要能够执行 stream.Read()、stream.Seek() 方法,这些方法都是 FileStream 类型的方法。

简单的类型转换不起作用,所以我在这里寻求帮助。

最佳答案

ReadSeekStream 类型的方法,而不仅仅是 FileStream。只是不是每个流都支持它们。 (我个人更喜欢使用 Position property 而不是调用 Seek,但它们归结为同一件事。)

如果您更喜欢将数据保存在内存中而不是将其转储到文件中,为什么不将其全部读入 MemoryStream 中呢?那支持寻求。例如:

public static MemoryStream CopyToMemory(Stream input)
{
// It won't matter if we throw an exception during this method;
// we don't *really* need to dispose of the MemoryStream, and the
// caller should dispose of the input stream
MemoryStream ret = new MemoryStream();

byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
ret.Write(buffer, 0, bytesRead);
}
// Rewind ready for reading (typical scenario)
ret.Position = 0;
return ret;
}

使用:

using (Stream input = ...)
{
using (Stream memory = CopyToMemory(input))
{
// Seek around in memory to your heart's content
}
}

这类似于使用 Stream.CopyTo .NET 4 中引入的方法。

如果您实际上想要写入文件系统,您可以做一些类似的事情,首先写入文件然后倒回流...但是您需要注意删除之后,以避免在您的磁盘上乱放文件。

关于c# - 在 C# 中将 Stream 转换为 FileStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3769067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com