我最近開發了一個 .NET Web 應用程式,它從我們網路上的某個設定位置下載 zip 檔案。我通過檢索內容流然后通過回傳 File() 將其傳回 View 來做到這一點。
來自 .NET Web App 的代碼我想模仿誰的行為:
public async Task<ActionResult> Download()
{
try
{
HttpContent content = plan.response.Content;
var contentStream = await content.ReadAsStreamAsync(); // get the actual content stream
if (plan.contentType.StartsWith("image") || plan.contentType.Contains("pdf"))
return File(contentStream, plan.contentType);
return File(contentStream, plan.contentType, plan.PlanFileName);
}
catch (Exception e)
{
return Json(new { success = false });
}
}
plan.response 在單獨的方法中構建,然后存盤為 Session 變數,以便它特定于用戶,然后在此處訪問以進行下載。
我現在正在開發一個 Windows 表單應用程式,它需要能夠從同一位置訪問和下載這些檔案。我能夠檢索回應內容,但我不知道如何繼續以在 Windows 表單應用程式中下載 zip。
有沒有辦法從接收內容流開始,我可以在 Windows 表單應用程式中使用類似的方法下載此檔案?這會很方便,因為訪問檔案最初需要登錄并驗證用戶,因此不能僅通過檔案路徑正常訪問。
uj5u.com熱心網友回復:
好吧,根據您要完成的任務,這里有一個非常簡單的示例,從 URL 下載檔案并將其保存在本地:
string href = "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip";
WebRequest request = WebRequest.Create(href);
using (WebResponse response = request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
Uri uri = new Uri(href);
string fileName = Path.GetTempPath() Path.GetFileName(uri.LocalPath);
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
dataStream.CopyTo(fs);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/332903.html
標籤:C# 视觉工作室 winforms 文件-io 系统网
