To download a file, you have to know its file identifier: FileId.
You find this property in the Animation, Audio, Document, Video, VideoNote, Voice, Sticker objects from a message.
For a Photo, you get an array PhotoSize[] with FileId for each resolution variants.
The last entry contains the best quality: message.Photo[^1].FileId
For ChatPhoto, there is a BigFileId for best quality, and SmallFileId for low resolution.
Downloading a file from Telegram is done in two steps:
- Get file information with
GetFilemethod. - Download the file with the
DownloadFilemethod
var fileId = update.Message.Video.FileId;
var tgFile = await bot.GetFile(fileId);
await using var stream = File.Create("../downloaded.mp4");
await bot.DownloadFile(tgFile, stream);For your convenience, the library provides a helper function that does both steps: GetInfoAndDownloadFile
await using var ms = new MemoryStream();
var tgFile = await bot.GetInfoAndDownloadFile(fileId, ms);Notes:
⚠️ Bot API can download files up to 20 MB only. For bigger files, consider using library WTelegramBot- When downloading into a
MemoryStream, remember to reset itsPositionbefore processing the content. - The
tgFile.FilePathreturned byGetFilecan be used to build the web URL accessing the file:https://api.telegram.org/file/bot<TOKEN>/<FilePath>.
(don't give this URL publicly! your TOKEN must remain secret!)
We recommend you first read the official documentation on sending files, it contains important information.
To upload a file from your machine, open the stream and call one of the sending methods:
await using var stream = File.OpenRead("../hamlet.pdf");
var message = await bot.SendDocument(chatId, stream, "The Tragedy of Hamlet,\nPrince of Denmark");You can also specify the public filename manually, or use a MemoryStream:
var buffer = File.ReadAllBytes("../hamlet.pdf");
await using var ms = new MemoryStream(buffer);
var message = await bot.SendDocument(chatId, InputFile.FromStream(ms, "Tragedy.pdf"),
"The Tragedy of Hamlet,\nPrince of Denmark");Be aware of limitation for this method - 10 MB max size for photos, 50 MB for other files. For bigger files, consider using library WTelegramBot
If the file is already stored somewhere on the Telegram servers, you don't need to reupload it: each file object has a FileId property. Simply pass this FileId as a parameter instead of uploading. There are no size limits for files sent this way.
var fileId = update.Message.Photo[^1].FileId;
var message = await bot.SendPhoto(chatId, fileId);Provide Telegram with an HTTP URL for the file to be sent. Telegram will download and send the file. 5 MB max size for photos and 20 MB max for other types of content.
var message = await bot.SendPhoto(chatId, "https://picsum.photos/640/480.jpg");