[英]Download file of any type in Asp.Net MVC using FileResult?
[英]ASP.NET MVC FileResult to file on disk
出於模擬目的,我想將FileResult輸出到磁盤上的實際文件中。
有沒有辦法獲取FileResult的內容並將其寫入文件? FileResult上的暴露屬性有點偏差。
我正在尋找類似的東西:
var file_result = controller.CsvExport();
file_result.ToFile(@"C:\temp.csv");
public static void WriteToFile(this FileResult fileResult, string fileName)
{
// what to implement here?
[...]
}
當您返回FileResult時,請使用以下子類之一...
然后你可以通過...訪問該文件
或者在擴展方法中,檢查它是哪個子類型,將其轉換為子類型,獲取文件路徑/內容/流並將其寫入輸出文件。
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's 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
這樣輸出就會更清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.