使用 C# 将 Stream 转换为 FileStream 的最佳方法是什么.
What is the best method to convert a Stream to a FileStream using C#.
我正在处理的函数有一个 Stream 传递给它,其中包含上传的数据,我需要能够执行 stream.Read()、stream.Seek() 方法,这些方法是 FileStream 类型的方法.
The function I am working on has a Stream passed to it containing uploaded data, and I need to be able to perform stream.Read(), stream.Seek() methods which are methods of the FileStream type.
简单的演员表不起作用,所以我在这里寻求帮助.
A simple cast does not work, so I'm asking here for help.
Read 和 Seek 是 Stream 类型上的方法,而不仅仅是文件流.只是不是每个流都支持它们.(我个人更喜欢使用 Position 属性而不是调用 Seek,但它们归结为同一件事.)
Read and Seek are methods on the Stream type, not just FileStream. It's just that not every stream supports them. (Personally I prefer using the Position property over calling Seek, but they boil down to the same thing.)
如果您更喜欢将数据保存在内存中而不是将其转储到文件中,为什么不将其全部读入MemoryStream?那支持寻求.例如:
If you would prefer having the data in memory over dumping it to a file, why not just read it all into a MemoryStream? That supports seeking. For example:
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 中引入.
This is similar to using the Stream.CopyTo method introduced in .NET 4.
如果你实际上想要写入文件系统,你可以做一些类似的事情,首先写入文件然后倒带流......但是你需要注意删除之后,以避免将文件弄乱您的磁盘.
If you actually want to write to the file system, you could do something similar that first writes to the file then rewinds the stream... but then you'll need to take care of deleting it afterwards, to avoid littering your disk with files.
这篇关于在 C# 中将流转换为 FileStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在条件下使用 RemoveAll 删除列表中的多个项目How to Remove multiple items in List using RemoveAll on condition?(如何在条件下使用 RemoveAll 删除列表中的多个项目?)
转换表达式树Convert Expression trees(转换表达式树)
当 IDENTITY_INSERT 设置为 OFF 时,无法为表“ClientCannot insert explicit value for identity column in table #39;ClientDetails#39; when IDENTITY_INSERT is set to OFF(当 IDENTITY_INSERT 设置为 OFF 时,
Linq 独特的 &最大限度Linq distinct amp; max(Linq 独特的 amp;最大限度)
使用 LinqPad 将字符串转换为 GuidCast string as Guid using LinqPad(使用 LinqPad 将字符串转换为 Guid)
Linq order by 在 select { } 中聚合Linq order by aggregate in the select { }(Linq order by 在 select { } 中聚合)