在 C# 中将流转换为 FileStream
- 作者: 鵞奀昆勥
- 来源: 51数据库
- 2022-12-15
问题描述
使用 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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
