c# - 如何通过 C# 将 IStream 存储到文件?

标签 c# istream

我正在使用返回 IStream 对象 (System.Runtime.InteropServices.ComTypes.IStream) 的第 3 方组件。我需要获取该 IStream 中的数据并将其写入文件。我已经成功完成了这项工作,但我对代码不太满意。

“strm”是我的 IStream,这是我的测试代码...

// access the structure containing statistical info about the stream
System.Runtime.InteropServices.ComTypes.STATSTG stat;
strm.Stat(out stat, 0);
System.IntPtr myPtr = (IntPtr)0;

// get the "cbSize" member from the stat structure
// this is the size (in bytes) of our stream.
int strmSize = (int)stat.cbSize; // *** DANGEROUS *** (long to int cast)
byte[] strmInfo = new byte[strmSize];
strm.Read(strmInfo, strmSize, myPtr);

string outFile = @"c:\test.db3";
File.WriteAllBytes(outFile, strmInfo);

至少,我不喜欢上面评论的 long 到 int 转换,但我想知道是否没有比上面更好的方法来获取原始流长度?我对 C# 有点陌生,所以感谢您的指点。

最佳答案

您不需要进行该转换,因为您可以从 IStream 源中分块读取数据。

// ...
System.IntPtr myPtr = (IntPtr)-1;
using (FileStream fs = new FileStream(@"c:\test.db3", FileMode.OpenOrCreate))
{
    byte[] buffer = new byte[8192];
    while (myPtr.ToInt32() > 0)
    {
        strm.Read(buffer, buffer.Length, myPtr);
        fs.Write(buffer, 0, myPtr.ToInt32());
    }
}

这种方式(如果有效)的内存效率更高,因为它只使用一个小内存块在流之间传输数据。

关于c# - 如何通过 C# 将 IStream 存储到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1572721/

相关文章:

c++ - 想要在新终端中运行 cpp 可执行文件,然后将文件发送到输入流

c++ - 非常基本的文件输入/输出

c++ - 自定义类的 Cin 参数

c# - Mango 快速应用程序切换和大量处理崩溃

c# - LINQ to Entities 无法识别方法 IsUserInCc

c# - ASP.NET MVC + 填充下拉列表

c# - 为什么 IEnumerable<T> 只有 "out"协变标志而不是 "in"c#?

c++ - 具有弹出功能的 istream

c++ - std::getline 从 istream 到 string[] 多次空白

c# - 在 OpenQA.Selenium (C#) 中找不到 WebDriverWait 类