1

入力パラメーターに基づいてサーバーから C# (サイズは 10 MB から 400 MB の間で変化する可能性があります) を使用して zip ファイルをダウンロードする必要があるという要件があります。たとえば、userId = 10 および year = 2012
のレポートをダウンロードします。Web サーバーはこれら 2 つのパラメーターを受け入れ、zip ファイルを返します。WebClient クラスを使用してこれを達成するにはどうすればよいですか?
ありがとう

4

2 に答える 2

6

これを行うには、WebClient クラスを拡張します。

class ExtWebClient : WebClient
    {

        public NameValueCollection PostParam { get; set; }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest tmprequest = base.GetWebRequest(address);

            HttpWebRequest request = tmprequest as HttpWebRequest;

            if (request != null && PostParam != null && PostParam.Count > 0)
            {
                StringBuilder postBuilder = new StringBuilder();
                request.Method = "POST";
                //build the post string

                for (int i = 0; i < PostParam.Count; i++)
                {
                    postBuilder.AppendFormat("{0}={1}", Uri.EscapeDataString(PostParam.GetKey(i)),
                                             Uri.EscapeDataString(PostParam.Get(i)));
                    if (i < PostParam.Count - 1)
                    {
                        postBuilder.Append("&");
                    }
                }
                byte[] postBytes = Encoding.ASCII.GetBytes(postBuilder.ToString());
                request.ContentLength = postBytes.Length;
                request.ContentType = "application/x-www-form-urlencoded";

                var stream = request.GetRequestStream();
                stream.Write(postBytes, 0, postBytes.Length);
                stream.Close();
                stream.Dispose();

            }

            return tmprequest;
        }
    }

使用法 : POST タイプのリクエストを作成する必要がある場合

class Program
{
    private static void Main()
    {
        ExtWebClient webclient = new ExtWebClient();
        webclient.PostParam = new NameValueCollection();
        webclient.PostParam["param1"] = "value1";
        webclient.PostParam["param2"] = "value2";

        webclient.DownloadFile("http://www.example.com/myfile.zip", @"C:\myfile.zip");
    }
}

使用法 : GET タイプのリクエストの場合、通常の Web クライアントを簡単に使用できます

class Program
{
    private static void Main()
    {
        WebClient webclient = new WebClient();

        webclient.DownloadFile("http://www.example.com/myfile.zip?param1=value1&param2=value2", @"C:\myfile.zip");
    }
}
于 2013-01-23T08:19:02.827 に答える
-1
string url = @"http://www.microsoft.com/windows8.zip";

WebClient client = new WebClient();

    client.DownloadFileCompleted +=    new AsyncCompletedEventHandler(client_DownloadFileCompleted);

    client.DownloadFileAsync(new Uri(url), @"c:\windows\windows8.zip");


void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    MessageBox.Show("File downloaded");
}
于 2013-01-23T08:24:42.703 に答える