I wanted one folder per Telegram group with every photo and video in it, numbered in the order they were posted. Telegram's cache doesn't give you that: files sit in folders by type, with names like 5229911934_y.jpg. Telegram Desktop's "Export chat history" is closer, but it's a one-off copy split into photos/ and video_files/, and you have to export again to pick up new posts.
So I built Chat Media Collector, a small Windows app that does exactly that.
You pick a chat, it shows how many photos and videos there are and how much space they need, and it saves them as 0001.jpg, 0002.mp4, 0003.jpg… Run it again next week and only the new posts are added, with the next numbers.
This post is about the parts that turned out more interesting to build than I expected.
The stack
- .NET 8 and WPF: one window, plus a tray icon for scheduled syncs
- WTelegramClient for Telegram's MTProto API. It's pure C#, so there's no native TDLib to ship.
- QRCoder for the "scan this with Telegram on your phone" sign-in
- An MSIX package for the Microsoft Store
1. Numbers that never move
The core promise is that 0041.jpg is the 41st photo or video in the chat, today and after every later run. That needs a memory, so each chat folder gets an index.csv:
Seq,File,MessageId,Date,Kind,Size,OriginalName,Album,AlbumId Three rules keep it honest:
- Numbers are fixed before anything downloads. The app lists the chat, gives every item a number and saves the index first. If a run stops halfway, the retry keeps the same numbers.
- The whole listing gets numbers, even what you skip. Save only photos today and the videos still get their numbers. They fill those gaps when you collect them later.
- New posts get the next numbers. A message already in the index keeps its number. Anything new goes after the last one.
Albums (several photos sent as one post) get a tag, so they stay together:
public static string NameFor(int seq, string extension, int album = 0) => seq.ToString("D4", CultureInfo.InvariantCulture) + (album > 0 ? " (album " + album.ToString(CultureInfo.InvariantCulture) + ")" : "") + extension; // 0041.jpg, or 0041 (album 7).jpg The number comes first on purpose: sorting by name in Explorer gives you the posting order.
2. A half-finished file never gets the real name
Downloads go to 0041.jpg.part and are renamed only when they're complete. That turns "is this one done?" into a single File.Exists check on the real name. A crash or a dropped connection can't leave a broken 0041.jpg behind for the next run to skip.
var part = destination + ".part"; try { await using (var output = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) await _source.DownloadAsync(chat, item, output, report, ct); File.Move(part, destination); } catch { FileLinker.TryDelete(part); throw; } 3. Reusing what's already on disk, for zero extra bytes
If you use Unigram, a popular Telegram client for Windows, it has often downloaded the media already. Downloading it again wastes time, and copying it doubles the disk space.
NTFS hard links fix the space problem. A hard link is a second name for the same file: no extra space, and the file stays even if Unigram later clears its cache. .NET doesn't wrap CreateHardLink, but it's one P/Invoke:
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); Hard links only work within one volume, so when the destination is on another drive the app copies instead (to a .part name, as above).
The harder part was finding the right file. Unigram is built on TDLib, which keeps media under %LOCALAPPDATA%\Packages\*Unigram*\LocalState\<account>\, in photos, videos, documents and animations. My first idea was to match on file size. With a cache of about 26,000 files, that picked the wrong video far too often. What works:
- Photos: TDLib names them after Telegram's photo id and size letter, so the app builds the expected name. Then the byte count proves it's the full-size copy and not a preview.
- Videos and files: the sender's original file name when there was one; otherwise Telegram's document id is the name. Name and size must both agree.
Building the lookup is cheap too. DirectoryInfo.EnumerateFiles() returns each file's size with the listing, so it never opens 26,000 files.
4. Always keep 1 GB free
Before each file, the app checks that the drive has room for it plus 1 GB. On my own PC, a completely full C: drive once brought Windows down, because the page file had nowhere to grow. A media downloader is exactly the kind of app that fills a drive overnight, so it stops cleanly with a message instead.
public const long ReserveBytes = 1L << 30; if (_freeBytes(folder) < item.Size + ReserveBytes) throw new LowDiskException(folder); 5. Instant thumbnails from a few hundred bytes
The chat preview shows a grid of thumbnails before anything is downloaded. Telegram helps here: each photo message carries a "stripped" thumbnail inline. It's a tiny JPEG with its 623-byte header removed, because that header is the same for every one. Put the header back, patch in the height and width, add the end-of-image marker, and WPF can show it right away. Telegram Desktop does the same thing (ExpandInlineBytes in its lib_ui).
if (stripped is not { Length: > 3 } || stripped[0] != 1) return null; var jpeg = new byte[Header.Length + stripped.Length - 3 + 2]; Header.CopyTo(jpeg, 0); jpeg[164] = stripped[1]; // the frame's height and width (the header has 0 there) jpeg[166] = stripped[2]; Buffer.BlockCopy(stripped, 3, jpeg, Header.Length, stripped.Length - 3); jpeg[^2] = 0xFF; // end of image jpeg[^1] = 0xD9; return jpeg; 6. Shipping to the Microsoft Store without installing the Windows SDK
I didn't want a multi-gigabyte SDK for two command-line tools. MakeAppx and MakePri are on NuGet in Microsoft.Windows.SDK.BuildTools, so the packaging script restores a tiny project that references that package and runs the tools from it. Things I learned on the way:
- Ship .NET inside the package. The Store has no .NET 8 desktop runtime to depend on, so the app is published self-contained. I used plain files rather than a single-file exe, so nothing gets unpacked to the temp folder on every start.
- Leave it unsigned. The Store signs the package when it publishes it, so you don't need a certificate.
- Watch MakePri's default config.
makepri createconfigadds a<packaging>section that moves the 200% images into a separateresources.scale-200.pri, which is meant for bundles. In a single .msix, high-DPI screens then get the blurry 100% icons. Removing that element fixes it:
& $makepri createconfig /cf $priConfig /dq en-US /pv 10.0.0 /o [xml]$config = Get-Content -Raw $priConfig $config.resources.RemoveChild($config.resources.packaging) | Out-Null $config.Save($priConfig) - "Start with Windows" works differently inside a package. The usual
HKCU\...\Runkey is virtualized for packaged apps, so writing to it silently does nothing. The package declares a startup task instead, and it shows up in Settings → Apps → Startup like any other. - The trial and the purchase come from
StoreContext. The catch for desktop apps: the Store's dialogs need to know which window they belong to.
_context = StoreContext.GetDefault(); WinRT.Interop.InitializeWithWindow.Initialize(_context, new WindowInteropHelper(owner).Handle); var license = await _context.GetAppLicenseAsync(); // IsTrial, TrialTimeRemaining 7. Asking for a rating at a good moment
The Store's rating dialog is easy to call and easy to annoy people with. The app asks once, ever, and only right after a run that went well:
public static bool ShouldAsk(DateTime? askedUtc, CollectResult? result) => askedUtc == null && result is { Cancelled: false, StoppedBecause: null } && result.Counts.Failed == 0 && result.Counts.FromCache + result.Counts.Downloaded >= MinSaved; // 20 One small WPF trap
The light and dark themes are two resource dictionaries with the same keys. Every colour is a DynamicResource, and switching themes swaps the dictionary while the app runs. That worked fine until a colour key and a style key had the same name (ScrollThumb), and the app crashed. Keep your brush keys and style keys apart.
Try it
Chat Media Collector is on the Microsoft Store for Windows 10 (1809 or later) and Windows 11, 64-bit, with a 7-day free trial. There's more on the website.
It's an unofficial app, not made by or affiliated with Telegram. Sign-in goes straight to Telegram, the session stays encrypted on your PC, and the app has no servers.
If you've solved any of these differently, especially the cache matching, I'd like to hear how in the comments.
This post was written by an AI assistant, working from the app's source code.

