How to download rest api response content into excel using windows forms application c#

Ashok Kumar 141 Reputation points
2023-01-27T07:47:50.0733333+00:00
I'm trying to download REST API response content as (original format) excel (.xlsx)

And I have used this method to return the response content

public static string DownloadFileName()

    {
        try
        {

            var client = new RestClient("https://www.connect2nse.com/extranet-api/member/file/download/1.0?segment=CM&folderPath=/Reports&filename=07141_AR1_Dec22.xlsx");
            client.Timeout = -1;
            var request = new RestRequest(Method.GET);
            request.AddHeader("Authorization", "Bearer eyJhbGciOweSUzI1NiJ9.eyJtZW1iZXJDZCI6IjA3MTQxIiwic3ViIjoiMDcxNDEiLCJsb2dpbklkIjoiYm5yaG8xIiwiaXNzIjoiYm5yaG8xIiwiZXhwIjoxNjc0ODA0NDE0LCJpYXQiOjE2NzQ4MDA4MTQsImp0aSI6ImEwY2U3NjNkLWY1OWUtNDY2Yy1hMmMwLTUwNGQwZDgzOTQwYiJ9.UCnkkvTTi9fZjWWak5deXgxPEqMG16FQP4Cy_u1cR0hQb-xQ4LAhbfpMtFz1WXQ4fz7ZmRhkR1i9JXY4w32lzQ");
            request.AddHeader("Cookie", "HttpOnly");
            var body = @"";
            request.AddParameter("text/plain", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            //Console.WriteLine(response.Content);

            return response.Content;

        }
        catch (Exception)
        {

            throw;
        }
    }

And I'm calling this method in `btnDownload_Click` event in windows forms application 

private void btnDownload_Click(object sender, EventArgs e)

    {
        string downloadfile = DownloadFileName();

        
        string _tradelogfile = Application.StartupPath + "\\07141_AR1_Dec22.xlsx";
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(_tradelogfile, true))
        {
            file.WriteLine(downloadfile);
        }

}


The 




So if I keep execute the program the file is downloading at specified location

Like below example 




While I'm opening the file it is throwing warning errors and file is not opening like below



[![File error 2][4]][4]


  [1]: https://i.stack.imgur.com/SrlMY.png
  [2]: https://i.stack.imgur.com/mH1Cr.png
  [3]: https://i.stack.imgur.com/gVtsV.png
  [4]: https://i.stack.imgur.com/svUuC.png


Please suggest me where I did the mistake and  how to save(download) this REST API response content as excel format(.xlsx).

Should I use any dll or is my code issue ?

Please suggest.

Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
1,454 questions
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,229 questions
0 comments No comments
{count} votes