2014-04-17 62 views
0

我想用C#和WebClient類在特定網站上上傳文件。我有這樣的代碼:C#使用webclient更改內容處置

Console.Write("\nPlease enter the URI to post data to : "); 

      String uriString = "http://www.noelshack.com/api.php"; 
      // String uriString = "http://127.0.0.1/upload.php"; 


      WebClient myWebClient = new WebClient(); 
      string fileName = lst_path[0]; 
      byte[] responseArray = myWebClient.UploadFile(uriString,"POST", fileName); 

      MessageBox.Show("\nretour:" + System.Text.Encoding.ASCII.GetString(responseArray)); 

但問題,網站上的文件輸入的名稱是「fichier」和Web客戶端發送「文件」作爲名字。

我希望它發送:

內容處理:表格數據; NAME = 「fichier」; filename =「csharp.jpg」 而不是: Content-Disposition:form-data; NAME = 「文件」;文件名=「csharp.jpg」

我沒有找到如何修改此字段,有些幫助嗎?

+0

反編譯'System.Net.WebClient.UploadFile',它使用'System.Net.WebClient。 OpenFileInternal',顯示'Content-Disposition:form-data; NAME = 「文件」;您需要使用其他方法 – cubetwo1729

回答

0

如果你有.NET 4.5 +,你可以使用HttpClient類做一個異步後:

async Task<string> UploadFileAsync(string[] lst_path) 
{ 
    string uriString = "http://www.noelshack.com/api.php"; 
    string fileName = lst_path[0]; 
    using (HttpClient client = new HttpClient()) 
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) 
    using (MultipartFormDataContent form = new MultipartFormDataContent()) 
    using (StreamContent sc = new StreamContent(fs)) 
    { 
     form.Add(sc, "fichier", fileName); 
     HttpResponseMessage response = await client.PostAsync(uriString, form); 
     response.EnsureSuccessStatusCode(); 
     return await response.Content.ReadAsStringAsync(); 
    } 
} 
+0

我通過http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c下載了httpclient,但在「等待「 - >」等待在此上下文中不存在「http://image.noelshack.com/fichiers/2014/16/1397765605-error.png – user3546480