[HttpGet] public IActionResult DownloadFile() { // Example: Converting a string to a byte array (could be from a DB or API) byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes("Hello, World!"); string fileName = "example.txt"; string contentType = "text/plain"; // Returns the file directly to the browser return File(fileBytes, contentType, fileName); } Use code with caution.
19 Aug 2016 — The ASP.NET MVC framework has got the built in FileResult . The MVC Controller itself has got the convenience function File(...) ( Stack Overflow How to download file from byte Array in asp.net core MVC? how to download byte array in c#
Downloading a byte array as a file is a common requirement in C# development, whether you're building a web application, a desktop tool, or a cloud service. The implementation varies slightly depending on your framework (ASP.NET Core, Web Forms, or Console), but the core logic involves converting binary data into a stream that a user's browser or local file system can recognize. 1. Downloading in ASP.NET Core MVC / Web API Downloading a byte array as a file is
byte[] data = // your byte array; string path = @"C:\Downloads\myFile.pdf"; // Creates a new file or overwrites an existing one System.IO.File.WriteAllBytes(path, data); Use code with caution. Downloading in ASP
It automatically sets the Content-Disposition header to attachment , prompting the browser to download instead of displaying the content.
In modern web applications, the most efficient way to serve a byte array as a downloadable file is by returning an IActionResult from your controller. The built-in File() method handles the necessary HTTP headers (like Content-Disposition ) for you.
Common types include application/pdf for PDFs, text/csv for spreadsheets, and application/octet-stream for generic binary files. 2. Saving Locally in C# (Console or Desktop)