c# - Splitting a String using String.Split()



Im trying to split a string into sub parts to pass into a linq database, but ive come up with a problem. The file is a .csv file so its split up by commas example :

1,Ms,Aleshia,Tomkiewicz,14 Taylor St,St. Stephens Ward,Kent,CT2 7PP,01835-703597,atomkiewicz@hotmail.com.

However some of the data contains commas in the data field like a county/address is split up with a comma however i dont want it to split i want it to keep that data all together for example address: London,Wimbledon.

im using this code currently to do the chopping:

 public static List<string> ReturnCSVFromWeb(string url)
            System.Net.WebClient client = new WebClient();
            string CSVContent = client.DownloadString(url);

            List<string> splitted = new List<string>();
            string csvFile = CSVContent;
            string[] tempStr;

            tempStr = csvFile.Split(',','\n');

            foreach (string item in tempStr)
                if (!string.IsNullOrWhiteSpace(item))

            return splitted;


2 Answers: 

There is no way to solve this problem unless you know ahead of time which data contains commas. A better option would be to have each entry in the csv surrounded by double quote, and then seperated by comma


If number of rows is fixed (M) and only address column has comma, you can do this:

  1. Split row
  2. Take first N1 columns before address
  3. Take last N2 columns after address
  4. Take M-N1-N2 columns from middle, join them - it's an address