You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# v15.7.1 Telegram Bot发文本文件报file must be non-empty如何解决

问题原因

写入MemoryStream内容完成后,流的Position属性会自动偏移到流的末尾位置。调用SendDocumentAsync方法传递流时,方法会从当前Position位置开始读取流内容,末尾位置向后没有可读取的数据,因此Telegram API返回「文件必须非空」的报错。你观测到的流长度为200是流的总长度,不代表当前可读取的内容长度。

解决方法

在完成流写入、flush操作后,手动将流的Position重置为0即可,修正后代码如下:

var csvFile = new StringBuilder();
foreach ( var person in persons)
{
    var output = new List<string>
    {
        person.Fardi.Name,
        person.Fardi.LastName,
        person.Fardi.PhoneNumber,
        person.Fardi.BrithYear.ToString(),
        person.Fardi.Father
    };
    csvFile.AppendLine(string.Join(_delimiter, output));
}
using var stream = new MemoryStream();
using var streamWriter = new StreamWriter(stream, Encoding.UTF8);
await streamWriter.WriteAsync(csvFile.ToString());
await streamWriter.FlushAsync();
// 新增以下代码重置流的读取位置到开头
stream.Position = 0;
await _botClient.SendDocumentAsync(new ChatId(chatId), new InputOnlineFile(stream, "test.txt"), replyMarkup: GetInlineKeyboard(buttons));

内容的提问来源于stack exchange,提问作者behroozbc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:27:00