我正在尝试阅读电子邮件附件,并且我收到"内存流无法展开"错误.我研究了一些,大多数解决方案似乎与动态确定缓冲区的大小有关,但我已经这样做了.我对内存流不是很熟悉,所以我想知道为什么这是一个问题.谢谢.
foreach (MailMessage m in messages)
{
byte[] myBuffer = null;
if (m.Attachments.Count > 0)
{
//myBuffer = new byte[25 * 1024]; old way
myBuffer = new byte[m.Attachments[0].ContentStream.Length];
int read;
while ((read = m.Attachments[0].ContentStream.Read(myBuffer, 0, myBuffer.Length)) > 0)
{
// error occurs on executing next statement
m.Attachments[0].ContentStream.Write(myBuffer, 0, read);
}
... more unrelated code ...
Run Code Online (Sandbox Code Playgroud)
Lua*_*aan 34
如果在预分配的字节数组上创建MemoryStream,则无法扩展(即,比您启动时指定的大小更长).相反,为什么不使用:
using (var ms = new MemoryStream())
{
// Do your thing, for example:
m.Attachments[0].ContentStream.CopyTo(ms);
return ms.ToArray(); // This gives you the byte array you want.
}
Run Code Online (Sandbox Code Playgroud)
小智 5
你需要更换线
m.Attachments[0].ContentStream.Write(myBuffer, 0, read);
Run Code Online (Sandbox Code Playgroud)
带有写入先前创建的行的行MemoryStream,例如
foreach (MailMessage m in messages)
{
byte[] myBuffer = null;
if (m.Attachments.Count > 0)
{
//myBuffer = new byte[25 * 1024]; old way
myBuffer = new byte[m.Attachments[0].ContentStream.Length];
int read;
MemoryStream ms = new MemoryStream();
while ((read = m.Attachments[0].ContentStream.Read(myBuffer, 0, myBuffer.Length)) > 0)
{
ms.Write(myBuffer, 0, read);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29106 次 |
| 最近记录: |