How to change this code from RestSharp to standard library C# ?

Paul 0 Reputation points
2023-03-22T11:32:39.06+00:00

Hi, Please could somebody help me to convert this code to the Visual Studio Standard Library?

It is about sending a file to one url via POST method. Thanks for your help.

string fileName = "C:\\temp\\schedule.csv";
var _client = new RestClient(https://www.domain.com);   // 1st part of URL
_client.Options.MaxTimeout = int.MaxValue;
var reQuest = new RestRequest("api/cust/upload/company", Method.Post);    // 2nd part of URL
reQuest.AddHeader("Content-Type", "text/csv");
reQuest.AddHeader("x-api-key", "24xxxxxxxxB.yyyy");
reQuest.AddFile("csvFile", fileName);
reQuest.AddHeader("Content-Type", "multipart/form-data");
RestResponse reSponse = _client.Execute(reQuest);
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,233 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2023-03-22T16:29:19.5666667+00:00

    it would be something like:

    
    var client = new HttpClient
    {
        BaseAddress = new("https://www.domain.com")
    };
    await using var stream = System.IO.File.OpenRead(fileName);
    using var request = new HttpRequestMessage(HttpMethod.Post, "api/cust/upload/company");
    using var content = new MultipartFormDataContent
    {
       { new StreamContent(stream), "csvFile", Path.GetFileName(fileName) },
    };
    request.Content = content;
    request.Headers.Add("x-api-key", "24xxxxxxxxB.yyyy");
    var response = await client.SendAsync(request);
    
    
    1 person found this answer helpful.

  2. Jack J Jun 24,286 Reputation points Microsoft Vendor
    2023-03-22T13:07:25.8333333+00:00

    @Paul, thanks for the feedback, you could try to use HttpWebRequest to replace restSharp to upload the file to a Url.

    Please refer to the second method Use FileStream with HttpWebRequest from this answer, which has a good example to tell you how to do it.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments