0

I am trying to recreate a curl command to upload a file in C# by using System.Net.WebClient or another method, and I'm just not having luck sending the file and the name-value stuff together, as well as the auth that curl uses. Anyone know the trick to this? I am limited to framework 4.0.

I just need to send a simple csv file up to a URL, as described here: http://quickfuseapps.com/docs/api/sdb_upload_csv

The command itself is:

curl -u username:password -F tablekey=username:customers -F mode=replace -F csv=@customerdata.csv http://quickfuseapps.com/api/1/sdb/upload/csv

I tried this using a code snippet and class I found, but it doesn't allow for the network credentials

Helpers.MultipartForm form = new Helpers.MultipartForm("http://quickfuseapps.com/api/1/sdb/upload/csv");
form.SetField("tablekey", "user:table");
form.SetField("mode", "replace");
// NO auth method to set credentials

form.SendFile(@"d:\test.csv");  form.SetField("tablekey", "user:table");
form.SetField("mode", "replace");
// NO auth method to set credentials

form.SendFile(@"d:\test.csv");

Here's code that will set form fields and auth, but doesn't also allow for the file upload

using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values.Add("app_id", "5gxWWnLlg");
    values.Add("tablekey", "user:table");                
    values.Add("dial_col", "PhoneNumber");
    values.Add("result_col", "outbound_result");

    client.Credentials = new NetworkCredential("user", "pwd");
    client.Encoding = Encoding.ASCII;

    //var response = client.UploadValues("http://quickfuseapps.com/api/1/outbound/queue", values);
    var response = client.UploadValues("http://quickfuseapps.com/api/1/outbound/queue/", "POST", values);

    var responseString = Encoding.Default.GetString(response);
}
cramopy
  • 3,459
  • 6
  • 28
  • 42
Jon R
  • 1
  • 1

1 Answers1

1

Here's an example of posting MultipartFormContent and HttpClient, not WebClient.

    using (var httpClient = 
        new HttpClient(new HttpClientHandler { Credentials = new NetworkCredential { <your credentials> } }) 
    {
        var byteArrayContent =   new ByteArrayContent(<.csv bytes read>);
        byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");

        var response = await httpClient.PostAsync(_importUrl, new MultipartFormDataContent
        {
             {new StringContent(<formField1Value>), "\"<formfield1>\""},
             // more form field and values
             {byteArrayContent, "\"file\"", "\"<your file name>\""}
        });
    }

This is for .net 4.5.

Note the \" in the MultipartFormDataContent. There is a bug in MultipartFormDataContent.

In 4.5.1 MultipartFormDataContent wraps the data with the correct quotes.

Fran
  • 6,440
  • 1
  • 23
  • 35
  • Can you see this please? https://stackoverflow.com/questions/48278333/php-curl-to-net-httprequest-files-uploading-to-server –  Jan 16 '18 at 12:11