How do i automate setting the properties of headers in a CSV file in c#

My program is hardcoded to know the headers of a CSV file.

 public class PeopleDataClass // here we say each value is going to be a property in my class
    {
        public string Name { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
    }

And using this i can then set how i want to change it into JSON/ XML in another function for example:

 public static void turnCsvIntoXml() // XML Data
    {
        var csvData = File.ReadAllLines(@"C:example\PeopleData.csv"); 
        XElement xml = new XElement("PeopleFromPersonData",
        from str in csvData
        let columns = str.Split(',')
        select new XElement("People",
            new XElement("Name", columns[0]),
            new XElement("AddressLine1", columns[1]),
            new XElement("AddressLine2", columns[2]))

        );
        //xml.Save(@"C:\Users\God\source\repos\WorkProject\PeopleData.csv"); // This will overwrite the file into XML Causing errors.

        Console.WriteLine(xml);
    }

My question is how do i set those properties automatically, so that a user can input their own file location (i have this set up already to take the users input as a variable and use that instead).

So if the user inputs a file of a CSV which has the headers 'Country, Year, Age, Mothers Name'. How do i make that process of setting the the headers as properties and then using the automatically set properties to convert the data into JSON/XML



Read more here: https://stackoverflow.com/questions/66321958/how-do-i-automate-setting-the-properties-of-headers-in-a-csv-file-in-c-sharp

Content Attribution

This content was originally published by noobi3 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: