从URL获取图片字节转Stream发送Discord时遇超时异常及方法适配咨询
问题解决:Discord发送图片Stream时的超时异常及Stream使用问题
1. 解决Timeouts are not supported on this stream异常
出现该异常的原因是MemoryStream本身不支持ReadTimeout属性,而Discord的AddFile方法内部尝试读取该属性,触发了异常。最简洁的解决方式是跳过字节数组转换步骤,直接通过HttpClient获取图片流:
using (var httpClient = new HttpClient()) { using (var imageStream = await httpClient.GetStreamAsync(response.Url)) { // 重置流的读取位置到起始处(GetStreamAsync返回的流默认位置在末尾) imageStream.Position = 0; await new DiscordMessageBuilder() .AddFile("image.png", imageStream, false) .SendAsync(commandContext.Channel); } }
如果必须基于已有的字节数组处理,可以自定义包装流重写ReadTimeout属性避免抛出异常,但这种方式不如直接使用GetStreamAsync高效:
public class NoTimeoutMemoryStream : MemoryStream { public override int ReadTimeout => Timeout.Infinite; public override int WriteTimeout => Timeout.Infinite; } // 使用示例 using (var imageBuffer = new NoTimeoutMemoryStream(imageContent)) { await new DiscordMessageBuilder().AddFile("image.png", imageBuffer, false).SendAsync(commandContext.Channel); }
2. 无需保存本地,直接发送Stream
AddFile方法并非仅接受FileStream,它提供了接受通用Stream类型的重载,完全可以直接使用内存中的流(如MemoryStream或网络流)发送内容,不需要将文件保存到本地存储,上述代码示例已验证这一点。
内容的提问来源于stack exchange,提问作者Marta flores calvo
相关产品推荐
相关产品推荐

