03.01.2015 Views

Complete set: Intro to C - Bill Buchanan

Complete set: Intro to C - Bill Buchanan

Complete set: Intro to C - Bill Buchanan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.3 Reading from a CSV file<br />

One of the best ways <strong>to</strong> transfer information between applications is <strong>to</strong> save the data<br />

separated by commas. This format is known as CSV (Comma Separated Variables).<br />

An example format is:<br />

1,5,6,7,4,5,6,7,10,5,4,3,2,1<br />

For this we can read the file one line at a time, and then split the string using the<br />

Split() method. This can be contained with the foreach statement, <strong>to</strong> parse each part<br />

of the split text. The code which fills the array v is:<br />

do<br />

{<br />

text=reader.ReadLine();<br />

if (text==null) break;<br />

foreach (string substring in text.Split(','))<br />

{<br />

v[i]=Convert.ToDouble(substring);<br />

i++;<br />

}<br />

} while (text != null);<br />

Program 3.5 shows the complete code <strong>to</strong> read the data from the CSV file (using the<br />

fillData()), and display it <strong>to</strong> the screen (using the showData() method).<br />

Program 3.5: Program3_5_ArrayGenerateDataWithCSV<br />

using System;<br />

using System.IO;<br />

duction <strong>to</strong> .NET<br />

<strong>Intro</strong><br />

namespace ConsoleApplication2<br />

{<br />

class ArrayExample02<br />

{<br />

const int ARRAYLIMIT=100;<br />

static void fillData(double[] v)<br />

{<br />

int i=0;<br />

FileInfo theSourceFile = new FileInfo("..\\..\\test.csv");<br />

StreamReader reader = theSourceFile.OpenText();<br />

string text;<br />

do<br />

{<br />

text=reader.ReadLine();<br />

if (text==null) break;<br />

foreach (string substring in text.Split(','))<br />

{<br />

v[i]=Convert.ToDouble(substring);<br />

i++;<br />

}<br />

} while (text != null);<br />

Agilent .NET Course: Arrays and Collections 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!