xamarinxamarin.formsxamarin.androidxamarin.iosxamarin.essentials

How to read any CSV file from my pcl folder in xamarin forms


I have one CSV file in my PCL folder, i want to get the path of that file so i can read the files using File.ReadAllLine(). Here is the code I have been used not not getting the file, as i have changed the file to the embedded resources I want this in string[] lines.

string[] lines = File.ReadAllLines("PrinterTestSample.Csv.UserData.csv");

Solution

  • You will need to get a stream from the assembly where the embedded resource is. Below a sample code on how to read it.

            // replace App with a class that is in the project where the embedded resource is.
            var assembly = typeof(App).GetTypeInfo().Assembly;
            // replace App3 with the namespace where your file is
            var stream = assembly.GetManifestResourceStream("App3.XMLFile1.xml");
    
            var lines = new List<string>();
    
            using var reader = new StreamReader(stream);
    
            while (reader.ReadLine() is { } line)
            {
                lines. Add(line);
            }