【问题标题】:How to store an IStream to a file via C#?如何通过 C# 将 IStream 存储到文件中?
【发布时间】:2009-10-15 14:29:49
【问题描述】:

我正在使用返回 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 to int 转换,但我想知道是否没有比上面更好的方法来获得原始流长度?我对 C# 有点陌生,所以感谢您的指点。

【问题讨论】:

    标签: c# istream


    【解决方案1】:

    您不需要进行这种转换,因为您可以从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());
        }
    }
    

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

    【讨论】:

    • Rubens - 感谢上述示例代码。它确实为我澄清了一些事情。不幸的是,自从我发布它以来,我一直无法对其进行测试,并且不会再有一段时间了。届时,我要么接受这个答案,要么在需要时发布更多说明。
    • myPtr 应该初始化为大于 0 的值,因为如果 init 值为 -1,它将永远不会进入 while 循环。
    • 您需要为该指针实际分配一些内存,而不仅仅是向其中抛出一个值,否则myPtr 将不会包含任何有用的东西。你必须读出价值; myPtr.ToInt32() 没有按照你的想法做。此外,读取的字节数是 long,因此您需要读取 Int64 值并进行转换。
    【解决方案2】:

    System.Runtime.InteropServices.ComTypes.IStream 是 ISequentialStream 的包装器。

    来自 MSDN:http://msdn.microsoft.com/en-us/library/aa380011(VS.85).aspx

    实际读取的字节数可以是 小于字节数 如果发生错误或 期间到达流的末尾 读操作。的数量 返回的字节数应始终为 与字节数相比 请求。如果字节数 返回的数量小于 请求的字节,它通常意味着 读取方法试图读取过去 流的结尾。

    本文档说,只要 pcbRead 小于 cb,您就可以循环读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      相关资源
      最近更新 更多