In a web environment, "downloading" means sending the file bytes back to the user's browser with the correct headers. In a Web API Controller:
string base64String = "SGVsbG8gV29ybGQ="; // Your Base64 data byte[] fileBytes = Convert.FromBase64String(base64String); Use code with caution. 2. Saving to a Local File (Console/Desktop)
Before you can "download" or save a file, you must decode the string into a byte array. C# makes this straightforward with the Convert class.
However, once that string reaches your C# backend or desktop app, you need to turn it back into a physical file. This guide covers the most efficient ways to handle this in .NET. 1. The Core Logic: Converting Base64 to Bytes
using System.IO; public void SaveBase64AsFile(string base64String, string outputPath) { byte[] fileBytes = Convert.FromBase64String(base64String); File.WriteAllBytes(outputPath, fileBytes); } Use code with caution. 3. Triggering a Download in ASP.NET Core (Web)
How to Download a File from a Base64 String in C# In modern web applications and APIs, you’ll often encounter data transferred as . This encoding method converts binary data (like images or PDFs) into text, making it easy to embed files directly into JSON or XML.
[HttpGet("download-report")] public IActionResult DownloadFile() { string base64String = "..."; // Get your string from a DB or service byte[] fileBytes = Convert.FromBase64String(base64String); string fileName = "report.pdf"; return File(fileBytes, "application/pdf", fileName); } Use code with caution. 4. Handling Data URIs (The "Prefix" Problem)