Downloading files
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.
Methods for downloading a file
Downloading a file from Telegram is done in two steps:
- Get file information with
GetFile
method. - Download the file with the
DownloadFile
method
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 itsPosition
before processing the content. - The
tgFile.FilePath
returned byGetFile
can be used to build the web URL accessing the file:https://api.telegram.org/file/bot<token>/<FilePath>
.
Uploading files
We recommend you first read the official documentation on sending files, it contains important information.
Upload local file
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
Upload by file identifier
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);
Upload by URL
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");