Search code examples
c#c#-4.0system.io.filesystem.io.fileinfo

How to Convert Binary file data to a physical type with a given MIME Type


I have a database table (tbl_document) which contains details of files which were uploaded into it over time.

I want to write a console application to download these files to a given location.

The table has three pieces of information, which I should use:

The FileContents in varbinary format; The MIME Type (contentType) for each file, in nvarchar format for example something like this:

application/x-zip-compressed application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document application/pdf application/pdf

In MVC, I would have done something like this to perform this task:

public FileContentResult DownloadFile()
{
                FileContentResult result = new FileContentResult(file.FileContents, file.ContentType);
                result.FileDownloadName = file.FileName;
                return result;
}

I have tried other ways to do this such as this one:

WebClient myWebClient = new WebClient();
 FileContentResult result = new FileContentResult(fileContents, contentType);

I couldn't really get to save the file using any of the above. Please could you help.

Many thanks.


Solution

  • I have actually solved it like this:

     // fileContents is the binary file being downloaded; I didn't need to use the MIME Types
            MemoryStream ms = new MemoryStream(fileContents);
            //write to file
            FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            ms.WriteTo(file);
            file.Close();
            ms.Close();