Skip to content

Loading a Local CSV File in Windows (Phone)

Lots of little side projects I work on are data visualizations and, unlike every other person in the data visualization game, I do them in XAML because 1) I’m good at XAML 2) I enjoy porting Python, Javascript, and R to C#.

But much of the data I want to visualize is something that I culled, compared, pared down and saved into a CSV file, so I just want to drop that file as a piece of content into my app directory & load it into my app at runtime.

Here is how you do that. First, we need to load our CSV file properly into the project. So create a folder for your data file and add an existing item

AddCSVFile

 

Select your file. Once in the project, select it and you’ll see that the “Build Action” for the file is set to “None”. Change that to “Content”.

SetToContent

 

Now add the following to read the CSV into a list of data objects.

List<MyDataObject> _dataObjects = new List<MyDataObject>();

var projectFolder = await Package.Current.InstalledLocation.GetFolderAsync("MyData");
var thisFile = await projectFolder.GetFileAsync("SampleCSV.csv");
using (StreamReader sr = new StreamReader(await thisFile.OpenStreamForReadAsync()))
{
    // lets just read the header out 
    string headerLine = sr.ReadLine();
    string line;
    // read a line while we have a line to read
    while ((line = sr.ReadLine()) != null)
    {
        string[] dataString = line.Split(new char[] { ',' });
        MyDataObject thisObject = new MyDataObject();
        // Add the appropriate properties
        _dataObjects.Add(thisObject);
    }
}