簡體   English   中英

您可以從 Windows 窗體應用程序中的 HttpContent 流下載文件嗎?

[英]Can you download a file from an HttpContent stream from within a Windows Forms Application?

我最近開發了一個 .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 窗體應用程序中使用類似的方法下載此文件? 這會很方便,因為訪問文件最初需要登錄並驗證用戶,因此不能僅通過文件路徑正常訪問。

好吧,根據您要完成的任務,這里有一個非常簡單的示例,從 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);
                }
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM