ASP.NET MVC FileResult to write to disk

For my mocking purposes, I would like to output the FileResult to an actual file on disk.

Is there a way to get the contents of a FileResult and write it to a file? The detected properties on FileResult are slightly on the thin side.

I am looking for something like:

var file_result = controller.CsvExport();

file_result.ToFile(@"C:\temp.csv");

public static void WriteToFile(this FileResult fileResult, string fileName)
{
    // what to implement here?
    [...]
}
+4
source share
1 answer

When you return a FileResult, use one of these subclasses ...

Then you can access the file through ...

  • FileContentResult.FileContents byte []
  • FilePathResult.FileName string / path
  • stream FileStreamResult.FileStream

, , , // .

public static void ToFile(this FileResult fileResult, string fileName)
{
    if (fileResult is FileContentResult)
    {
        File.WriteAllBytes(fileName, ((FileContentResult)fileResult).FileContents);
    }
    else if (fileResult is FilePathResult)
    {
        File.Copy(((FilePathResult)fileResult).FileName, fileName, true); //overwrite file if it already exists
    }
    else if (fileResult is FileStreamResult)
    {
        //from http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file-in-c
        using (var fileStream = File.Create(filename))
        {
            var fileStreamResult = (FileStreamResult)fileResult;
            fileStreamResult.FileStream.Seek(0, SeekOrigin.Begin);
            fileStreamResult.FileStream.CopyTo(fileStream);
            fileStreamResult.FileStream.Seek(0, SeekOrigin.Begin); //reset position to beginning. If there any chance the FileResult will be used by a future method, this will ensure it gets left in a usable state - Suggestion by Steven Liekens
        }
    }
    else
    {
        throw new ArgumentException("Unsupported FileResult type");
    }
}

, , ToFileOnDisk ToFile, , .

+8

All Articles