C#使用webclient更改内容处置

时间:2014-04-17 18:42:35

标签: c# upload webclient content-disposition

我想使用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”,webclient发送“file”作为名称。

我希望发送:

内容 - 处置:表单数据; NAME = “fichier”;文件名= “csharp.jpg” 代替 : 内容处理:表格数据; NAME = “文件”;文件名= “csharp.jpg”

我没有找到如何修改此文件,请帮助一下?

1 个答案:

答案 0 :(得分: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();
    }
}