无法访问 MemoryStream 的内部缓冲区
在处理剪贴板数据时, ms.GetBuffer() 语句出现异常,代码如下:
//检索当前位于系统剪贴板中的数据
IDataObject ido = Clipboard.GetDataObject();
//获取存储在 IDataObject 实例中的数据所关联的或可以转换为的所有格式的列表
String[] fmtList = ido.GetFormats();
//循环输出所有格式的列表
for (int i = 0; i < fmtList.GetLength(0); i++)
{
String fmt = fmtList[i];
tb_result.Text += fmt + "\r\n";
}
String dibFmt = "DeviceIndependentBitmap";
if (fmtList.Contains(dibFmt) && ido.GetDataPresent(dibFmt))
{
Object obj = ido.GetData(dibFmt);
MemoryStream ms = (MemoryStream)obj;
MemoryStream ms2 = new MemoryStream();
//构造固定文件头
byte[] bmpHeader = new byte[] { 0x42, 0x4D, 0x96, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00 };
//将文件头和文件数据写入内存流
ms2.Write(bmpHeader, 0, bmpHeader.Length);
ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
解决方法:
通过读取的方式获取:
MemoryStream ms = (MemoryStream)obj;
byte[] buff = new byte[ms.Capacity];
if (ms.CanRead)
{
ms.Read(buff, 0, ms.Capacity);
}