Search code examples
c#csvdatatabledataset

Convert request body to datatable or dataset in C#


I am making a azure function that takes a request body. with the following format.

"10","Name","112","50012","Activity","08/02/2021","3:20","3:10","" "10","Name","","","Break","08/02/2021"," - ","0:11","Break" "10","Name","112","50012","Activity","08/02/2021","2:09","2:09",""

The first pair of strings is the worker ID, second is the name, 3rd is the id of the customer, 4th is the activity id, 5th is the activity, 6th is the date, 7th is the raw amount of hours worked, 8th is calculated amount of hours worked and last indicates if it was a break.

Short there is 9 sets of string on each line and there is no telling how many lines there are. Now i want to convert this to a datatable and then to a dataset. So far i have only been able to read the body like this.

        using(var reader = new StreamReader(req.Body))
        {
            var ResponseBody = reader.ReadToEnd();

            return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
        }

I hope you can help me. Thanks in advance.


Solution

  • I am suggesting you a sample approach and you can take this as reference for solving your actual problem.

    So you have to read the data line by line and split the data.

    DataTable dt = new DataTable();
    string[] columns = [];//column names as you have mentioned in your data there are no columns 
    foreach (string column in columns)
    {
        dt.Columns.Add(column);
    }
    using (StreamReader reader = new StreamReader(strFilePath))
    {
        while (reader.EndOfStream == false)
        {
            string[] rows = reader.ReadLine().Split(',');
            DataRow dr = dt.NewRow();
            for (int i = 0; i < columns.Length; i++)
            {
                dr[i] = rows[i];
            }
            dt.Rows.Add(dr);
        }
    }
    

    Assumption: I’m assuming that you have no comma in between values