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

如何用C#的WTelegramClient获取参数下载Telegram用户的文本文档

解决WTelegramClient下载用户文本文档的参数获取问题

获取Document参数

遍历你已获取的消息历史数组,筛选出包含文档的消息即可拿到该参数:

  • 先判断消息类型为Message,再检查其Media属性是否为MessageMediaDocument类型
  • 从MessageMediaDocument的document字段直接提取需要的Document对象

示例代码:

Messages_MessagesBase history = await this.client.Messages_GetHistory(peer);
Document targetDoc = null;

foreach (var msgItem in history.Messages)
{
    if (msgItem is Message message && message.Media is MessageMediaDocument mediaDoc)
    {
        // 可根据文档名称筛选目标文件,比如:
        // var fileName = mediaDoc.document.attributes.OfType<DocumentAttributeFilename>().First().file_name;
        // if (fileName == "你要找的文档名.txt")
        targetDoc = mediaDoc.document;
        break; // 找到目标文档后终止循环
    }
}

获取Stream outputStream参数

在Windows Form程序中,可通过SaveFileDialog让用户选择保存路径,再创建FileStream作为输出流:

示例代码:

if (targetDoc != null)
{
    using (SaveFileDialog saveDialog = new SaveFileDialog())
    {
        // 设置文件格式筛选器
        saveDialog.Filter = "文本文档 (*.txt)|*.txt|所有文件 (*.*)|*.*";
        // 自动填充文档原始文件名
        var fileNameAttr = targetDoc.attributes.OfType<DocumentAttributeFilename>().FirstOrDefault();
        if (fileNameAttr != null)
            saveDialog.FileName = fileNameAttr.file_name;

        if (saveDialog.ShowDialog() == DialogResult.OK)
        {
            using (Stream outputStream = File.OpenWrite(saveDialog.FileName))
            {
                // 执行下载
                await client.DownloadFileAsync(targetDoc, outputStream);
                MessageBox.Show("文档下载完成");
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:01:01