c# - How do I separate each line of a .csv file into a string list> -


i new c# , attempting read in .csv file , put each line of text in separate list item can sort later.

the .csv file organised so:

1;"final60";"united kingdom";"2013-12-06 15:48:16";
2;"donnyr8";"netherlands";"2013-12-06 15:54:32"; etc

this first attempt doesn't work.it shows no errors in visual studios 2010 when run console program displays following exception instead of list. exception of type 'system.outofmemoryexception' thrown. bizarre because .csv file contains small list.

try { // load csv file using (streamreader file = new streamreader("file.csv"))       {        string line = file.readline();        list<string> filelist = new list<string>();        // lines file until end of          // file reached.         while (line != null)        {            filelist.add(line);          }         foreach (string filelistline in filelist)          {             console.writeline(filelistline);          }        } } catch (exception e) {   // let user know went wrong.    console.writeline("the file not read:");    console.writeline(e.message); } 

so approaching correct way?

if file loading isn't big can use file.readalllines:

list<string> list = file.readalllines("file.csv").tolist(); 

as servy pointed out in comment better use file.readlines method.

file.readlines - msdn

the readlines , readalllines methods differ follows: when use readlines, can start enumerating collection of strings before whole collection returned; when use readalllines, must wait whole array of strings returned before can access array. therefore, when working large files, readlines can more efficient.

if need list<string> can do:

list<string> list = file.readlines("file.csv").tolist(); 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -