Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how o convert byte array any to its original file when downloading the any type of file like
pdf, excel,png,jpg like that

What I have tried:

C#
string fileName = "file";

byte[] pdfasBytes = Encoding.ASCII.GetBytes(file);
Response.Clear();
MemoryStream ms = new MemoryStream(pdfasBytes);
Response.ContentType = "application/pdf";
Response.Headers.Add("content-disposition", "attachment;filename=" + fileName);
// Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.Buffer = true;
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();

return file;
Posted
Updated 10-Mar-21 5:52am
v3

All files are byte arrays: that is all that a hard disk knows how to store.
It's the organisation of the data in those bytes that controls how an app works with it: a text file will be limited to just text characters rather than the "whole byte" value; a BMP file will be bytes starting with the characters "BM"; and EXE file is bytes starting with "MZ"; a CSV file is a text file with strings separated by commas; a DOCX file is a ZIP file with a different extension that contains other files and so on.

Basically, to return it to it's original file, all it needs is the right file name and extension - the extension controls which apps will open it by default, but doesn't change the actual data in the byte stream.
 
Share this answer
 
Quote:
C#
string fileName = "file";
byte[] pdfasBytes = Encoding.ASCII.GetBytes(file);
Well, there's your problem. You're not reading any bytes from the specified file; you're taking the string "file" and getting an array of ASCII code-points representing the characters in that string.

The simplest option is to throw your code away and use the Response.TransmitFile[^] method instead:
C#
string virtualPath = "~/downloads/your-file.pdf";
string physicalPath = Server.MapPath(virtualPath);
Response.ContentType = "application/pdf";
Response.Headers.Add("content-disposition", "attachment;filename=" + Path.GetFileName(physicalPath));
Response.TransmitFile(physicalPath);

If you really want to read the file into memory first, then you'll need to actually read the file:
C#
string virtualPath = "~/downloads/your-file.pdf";
string physicalPath = Server.MapPath(virtualPath);
byte[] pdfasBytes = System.IO.File.ReadAllBytes(physicalPath);
NB: This is horribly inefficient. Every request is going to end up storing the entire contents of the file in memory twice - once for your byte array, and once for the buffered response. Your server will very quickly run out of memory.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900