silverlight下载文件

2015-12-22 11:33:41来源:CSDN作者:xiongdong2530人点击

完整的代码如下:

 

/// <summary>

        /// 

        /// </summary>

        private void Download_Click(object sender, RoutedEventArgs e)

        {

            string filePath = "http://localhost:34270/ClientBin/test.rar";

 

            WebRequest request = WebRequest.Create(filePath);

 

            //

            bool needDownload = false;

 

            SaveFileDialog sfd = new SaveFileDialog();

 

            string extension = System.IO.Path.GetExtension(filePath);

            sfd.Filter = string.Format("*{0}| *{0}", extension);

 

            if (sfd.ShowDialog() == true)

            {

                needDownload = true;

            }

 

            if (needDownload)

            {

                request.BeginGetResponse((responseAsyncCallBack) =>

                    {

                        this.Dispatcher.BeginInvoke(() =>

                            {

                                using (Stream openFileStream = sfd.OpenFile())

                                {

                                    #region 获取response bytes

 

                                    WebResponse response = request.EndGetResponse(responseAsyncCallBack);

                                    Stream responseStream = response.GetResponseStream();

 

                                    Byte[] bufferBytes = new Byte[responseStream.Length];

                                    responseStream.Read(bufferBytes, 0, bufferBytes.Length);

 

                                    #endregion

 

                                    openFileStream.Write(bufferBytes, 0, bufferBytes.Length);

                                    openFileStream.Flush();

                                }

                            });

                    }, null);

            }

        }

作者:LoveJenny出处:http://www.cnblogs.com/LoveJenny/    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台