簡體   English   中英

如何使用 C# 在 Windows 應用程序中使用 SaveFileDialog 在來自 HttpClient 的本地計算機上保存 Zip 文件?

[英]How to save Zip file on local machine which is coming from HttpClient using SaveFileDialog in Windows application using C#?

我想存儲由ToRetrieve方法檢索的 zip 文件,並使用SaveFileDialog控制器將其存儲在本地計算機上,並使用 C# 編寫的 Windows 應用程序。

這是我的代碼:

if (!string.IsNullOrEmpty(FileName))
{
    APIOrderMethods objAPIOrderMethods = new APIOrderMethods();
    saveFileDialog1.Filter = "zip files (*.zip)|*.zip|All files (*.*)|*.*";
    saveFileDialog1.Title = FileName;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK) 
    {
        Stream stream = objAPIOrderMethods.ToRetrieve(FileName, ServicelURL, useName, password);
        Stream streamToWriteTo = File.Open(saveFileDialog1.FileName, FileMode.Create, FileAccess.ReadWrite);
        stream.CopyToAsync(streamToWriteTo);
    } 
               
    label12.ForeColor = Color.Green;
}

但我收到此錯誤:

異常:“無法訪問關閉的流。”

ToRetrieve獲取 Zip 文件的方法:

public  Stream ToRetrieve(string Filename, string serviceURL, string Username, string Password)
{
    Stream Result = null;
    var _saveDir = System.Configuration.ConfigurationManager.AppSettings["Save"];

    try
    {
        using (HttpClient client = new HttpClient())
        {
            string url = "https://codeload.github.com/tugberkugurlu/ASPNETWebAPISamples/zip/master";

            using (HttpResponseMessage response =  client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result)
            using (Stream streamToReadFrom =  response.Content.ReadAsStreamAsync().Result)
            {
                Result = streamToReadFrom;
            }
        }
    }
    catch (Exception ex)    
    {
        throw;
    }

    return Result;
}

問題在於方法ToRetrieve

streamToReadFrom在 using 語句中時,將調用Dispose方法。

由於結果包含引用,您將返回一個關閉的流。

暫無
暫無

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

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