Search code examples
c#asp.netfile-uploadmemorystreamfileinfo

Upload a file, MemoryStream vs FileInfo


I have to generate some files in my asp.net web application and send it to the client. So I made a method who work with a memory stream and send the buffer to the http response.

It is working fine but I just read another code and the guy is using a fileInfo. So if I understand correctly FileInfo is a "real" file written on the server disk.

So what is the best choice? (if there's one) What are questions I have to ask me? Is it about the size of the file?

Note that I don't care about storing the file, once he is send I don't have to have it on the server.


Solution

  • FileInfo is only a pointer to a file already stored on a file system. If you want to access its contents you need to use a stream. So in your case if you don't want to save the file on the server you could use a MemoryStream and write it to the response. A Stream is also a pointer to some data. A MemoryStream is a pointer to a data stored in memory. So you will need to first load this data in memory.

    A better way is to directly write to the Response object in chunks. This way you don't need to load the whole file contents in memory. But this will depend on how you are generating the file.