Generating form data for an API request

ADeBok 106 Reputation points
2021-05-21T08:03:18.427+00:00

Hi I am trying to write a C# client for this API: https://www.directdebit.co.za/api/dos.svc

On their endpoint for "/batch/eft/" they want me to send them a file with the formData Paramater Type. As far as I understand I should be using the MultipartContent class to do this. I've managed to read the file into a string variable, I just need to assign that to a multipart/formData paramater somehow. Here's my code so far:

    // Upload a file to Direct Debit via the API
    public async void UploadFile(string filePath)
    {
        if (!File.Exists(filePath))
        {
            throw new ArgumentException($"{filePath} does not exist");
        }

        var sb = new StringWriter();
        using (var fs = File.OpenRead(filePath))
        {
            var b = new byte[1024];
            while (fs.Read(b, 0, b.Length) > 0)
            {
                sb.Write(b);
            }
        }

        var content = sb.ToString();

        var hc = GenerateHttpClient();
        var postBody = new MultipartContent();

        // I am a little confused. What do I do now?

        var resp = await hc.PostAsync(url + "/batch/eft", postBody);
        resp.EnsureSuccessStatusCode();
    }

Thanks in advance.
Arie

Developer technologies C#
0 comments No comments
{count} vote

Accepted answer
  1. ADeBok 106 Reputation points
    2021-05-21T11:29:47.063+00:00

    I figured it out. I should have used MultipartFormDataContent, instead of just MultipartContent. The correct code is then:

            var postBody = new MultipartFormDataContent
            {
                {new ByteArrayContent(content.ToArray()), "file_data", Path.GetFileName(filePath)}
            };
    
            var resp = await hc.PostAsync(_url + "/batch/eft", postBody);
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. J4cuza 1 Reputation point
    2021-05-24T07:01:21.897+00:00

    Thanks for posting the answer, I was also struggling with sending a file.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.