我正在使用返回 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/