C# winform 上傳文件到服務器


1.首先要在服務器端新建一個網站axpx頁

然后再網站的后台寫代碼獲取winform傳過來的文件名。

聲明:這個方法雖然最簡單最省事,但是上傳大文件可能會報錯,我的機器是10M,

超過10M就會提示報錯。

 

 

[c-sharp]  view plain copy print ?
 
  1. //這是網站的后台代碼,獲取winform傳過來的文件名  
  2. protected void Page_Load(object sender, EventArgs e)  
  3.  {  
  4.      foreach (string f in Request.Files.AllKeys)  
  5.      {  
  6.          HttpPostedFile file = Request.Files[f];  
  7.          file.SaveAs(@"d:/" + file.FileName);  
  8.      }  
  9.  }  

 

 

2.至於winform那邊,就只是要調用一下WebClient的UploadFile方法了。

WebClient 屬於 using System.Net; 空間下。

 

 

[c-sharp]  view plain copy print ?
 
  1. public bool uploadFileByHttp(string webUrl,string localFileName)  
  2.         {  
  3.             // 檢查文件是否存在  
  4.             if (!System.IO.File.Exists(localFileName))   
  5.             {  
  6.                 MessageBox.Show("{0} does not exist!", localFileName);  
  7.                 return false;  
  8.             }  
  9.             try  
  10.             {  
  11.                 System.Net.WebClient myWebClient = new System.Net.WebClient();  
  12.                 myWebClient.UploadFile(webUrl, "POST", localFileName);  
  13.             }  
  14.             catch  
  15.             {                 
  16.                 return false;  
  17.             }  
  18.             return true;  
  19.         }  
  20.   
  21. //調用方法屬於遠程服務器的地址,和保存文件的地址  
  22. this.uploadFileByHttp(" http://localhost:1878/UploadFileWebSite/UploadFile.aspx", @"D:/1.txt"); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM