0

I am trying to convert the following cURL statement into a pot request using HttpWebRequest.

curl -F datafile=@C:\Path\Students.csv -F account=accountName -F username=un -F key=acctkey -F type=1 -F format=CSV -F date=8 -F header=No -F email=email@school.org -F description=student_data_update https://webaddress.com/district_import.php

I have tried many different suggestions off this, and other sites. This one seems to be closest to correct, however I'm not getting there. I'm creating a postString for the cURL parameters. The postString is built from parameters sent to the function, but this is what it would look like.

    string postString = "account=accountName&type=1&format=CSV&date=8&header=No&description=student_data_update&username=un&key=acctkey&email=email@school.org";

My code looks like this:

            HttpWebRequest requestToServerEndpoint =
            (HttpWebRequest)WebRequest.Create(new Uri(url + @"/"));


            string boundaryString = "----SomeRandomText";

            // Set the http request header \\
            requestToServerEndpoint.Method = WebRequestMethods.Http.Post;
            requestToServerEndpoint.ContentType = "multipart/form-data; boundary=" + boundaryString;
            requestToServerEndpoint.KeepAlive = true;
            requestToServerEndpoint.Credentials = new System.Net.NetworkCredential(un, p);
            requestToServerEndpoint.Headers.Add("account", "acctName");

            // Use a MemoryStream to form the post data request,
            // so that we can get the content-length attribute.
            MemoryStream postDataStream = new MemoryStream();
            StreamWriter postDataWriter = new StreamWriter(postDataStream);

            // Include value from the myFileDescription text area in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
            "myFileDescription",
            "A sample file description");

            // Include the file in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data;"
            + "name=\"{0}\";"
            + "filename=\"{1}\""
            + "\r\nContent-Type: {2}\r\n\r\n",
            "myFile",
            Path.GetFileName(file),
            Path.GetExtension(file));
            postDataWriter.Flush();
            // Read the file
            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            byte[] bytes = Encoding.ASCII.GetBytes(postString);
            postDataStream.Write(bytes, 0, bytes.Length);
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                postDataStream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
            postDataWriter.Flush();

            // Set the http request body content length
            requestToServerEndpoint.ContentLength = postDataStream.Length;

            // Dump the post data from the memory stream to the request stream
            using (Stream s = requestToServerEndpoint.GetRequestStream())
            {
                postDataStream.WriteTo(s);
            }
            StreamReader responseReader = new StreamReader(requestToServerEndpoint.GetResponse().GetResponseStream());
            string responseData = responseReader.ReadToEnd();
            postDataStream.Close();
            responseReader.Close();
            requestToServerEndpoint.GetResponse().Close();

When reviewing the error from the response. My error is : Missing account. I have added into the headers, and the first parameter in my postString. What am I missing?

Katie
  • 5
  • 3

1 Answers1

0

Something like this should do the trick if the webserver is setup to take a file anonymously. Most servers won't. So be ready to add credentials to authenticate the WebClient to the server when you move to production.

private void PostFile(string URL, string myFilePath)
{
     // test for the file
     if (System.IO.File.Exists(myFilePath) == false)
         throw new System.IO.FileNotFoundException("Can't find " + myFilePath);

     // get the file
     var csvFile = System.IO.File.ReadAllBytes(myFilePath);

    // post the file to the server using the webclient
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
        client.UploadData(URL, csvFile);
     }
}
Juls
  • 658
  • 6
  • 15
  • Thank you so much for your suggestion. This did not mention the parameters for this request so I tried to add them using these suggestions. https://stackoverflow.com/questions/514892/how-to-make-an-http-get-request-with-parameters That did not work but I tried to continue with the WebRequest that you suggested and did something like this: https://stackoverflow.com/questions/11048258/uploadfile-with-post-values-by-webclient I'm now getting the error : Missing file. – Katie Aug 10 '18 at 20:19