Click here to Skip to main content
16,004,969 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am reading a text file which contains comma separated values.
The content in the file will be as such:
ad,af,,,EndofReport
I want to read only the data with the comma separated contents.
ie:
ad,af,EndofReport without empty values in the comma separated string.

What I have tried:

Core Code as below:
string[] lines = System.IO.File.ReadAllLines(filePath);
                                    for (int j = 0; j < lines.Length; j++)
                                    {
                                      
                                        StdReportData = lines[j];
string[] words;
 words = StdReportData.Split(',');

}
Posted
Updated 13-Aug-18 20:02pm

You can change
C#
words = StdReportData.Split(',');

to
C#
words = StdReportData.Split(',',StringSplitOptions.RemoveEmptyEntries);


Further reading: String.Split Method (Char[], StringSplitOptions) (System)[^]
 
Share this answer
 
The best solution is "don't" - CSV data isn't just "separated by comma" it can also contain quoted strings, which can legitimately contain commas.

Instead of "rolling your own" solution here, have a look at this: A Fast CSV Reader[^] - it does all the hard work for you!
 
Share this answer
 
Comments
TommoDotCommo 14-Aug-18 2:03am    
Try as below:
C#
string[] lines = System.IO.File.ReadAllLines(filePath);
            for (int j = 0; j < lines.Length; j++)
            {

                var StdReportData = lines[j];
                string[] words;
                words = StdReportData.Split(',')
                    .Select(x => x.Trim())
                    .Where(x => !string.IsNullOrWhiteSpace(x))
                    .ToArray();

            }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900