简体   繁体   中英

How to read from a delimited text file (csv) in Xamarin Forms

I have a csv that is delimited by "|" (bc I have commas in my values). I imported the file into the PCL and set its build to embedded resource, but I am unclear on how to read this file and delimit it, etc. I've found examples of doing this online, but something is always missing, like a funciton that isn't defined or a function that's not part of Xamarin Forms' .NET. So if someone could just type up a really simple loop to read a csv, delimit by |, and put the values into an array, that would be awesome. Thanks so much!

Among several libraries out there which I tested, I could install the " CsvTools " by Mike Stall in PCL project.

Sample CSV file:

Id|FirstName|LastName|IsRegistered
10248|George|Scheffer|true
10249|Linda|Watson|false
10250|John|Deyoe|false
10251|Amy|Bannister|true

Supposing there is a file named "users.csv" in PCL root directory and set its BuilsAction as EmbeddedResource (as you already did):

Here is our model to convert each row of CSV file to it:

public class User
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsRegistered { get; set; }
    }

And here is all functionality to read this CSV file and get a collection of User:

var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("XFTest.users.csv");

var csvData = DataTable.New.ReadLazy(stream);
List<User> users = csvData.RowsAs<User>().ToList();

Note that there wasn't any need to define any delimeter here and it worked for "|", and if it was a comma it would work as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM