webclient上傳下載文件

定義WebClient使用的操做類: 操做類名稱WebUpDown服務器

WebClient上傳文件至Ftp服務:文件上傳

//// <summary> string

        /// WebClient上傳文件至Ftp服務io

        /// </summary> ast

        /// <param name="fileNamePath">文件名,全路徑格式</param> cli

        /// <param name="uriString">服務器文件夾路徑</param> ftp

        public static void UpLoadFile(string fileNamePath, string uriString)object

        {file

            string NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));下載

            uriString = uriString + NewFileName;

 

            //建立WebClient實例 

            WebClient myWebClient = new WebClient();

 

            //指定用戶名和密碼

            myWebClient.Credentials = new NetworkCredential("username", "password");

 

            try

            {

                //上傳文件

                myWebClient.UploadFile(new Uri(uriString), fileNamePath);

            }

            catch (Exception ex)

            {

                MessageBox.Show("文件上傳失敗,失敗緣由:" + ex.Message);

            }

            finally

            {

                myWebClient.Dispose();

            }

        } 

 

 

 

下載服務器文件至客戶端:

        /// <summary> 

        /// 下載服務器文件至客戶端 

        /// </summary> 

        /// <param name="URL">被下載的文件地址,絕對路徑</param> 

        /// <param name="Dir">另存放的目錄</param> 

        public static void Download(string URL, string Dir)

        {

            WebClient client = new WebClient();

            client.Credentials = new NetworkCredential("username "," password ");

            string Path = Dir;   //另存爲的絕對路徑+文件名 

 

            try

            {

                client.DownloadFile(new Uri(URL), Path);

            }

            catch (Exception ex)

            {

                MessageBox.Show("文件下載失敗,失敗緣由:" + ex.Message);

            }

            finally

            {

                client.Dispose();

            }

        }

 

 

調用方法:

/// <summary>

        /// WebClient上傳到Ftp服務

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void Button_Click_5(object sender, RoutedEventArgs e)

        {

            WebUpDown.UpLoadFile(@"C:\123.txt",@"ftp://localhost//");

        }

 

        /// <summary>

        /// WebClient使用Ftp服務下載到客戶端

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void Button_Click_6(object sender, RoutedEventArgs e)

        {

            WebUpDown.Download(@"ftp://localhost//123.txt", @"C:\123.txt");

        }

相關文章
相關標籤/搜索