How to Read text File in Xamarin

Ronald GANS 136 Reputation points
2022-12-26T23:48:52.84+00:00

Doing this in C# for Windows is trivial, but for Xamarin (Android), it's not. I want the user to be able to navigate around their device, select a file and read it all.

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2022-12-27T02:11:18.89+00:00

    Hello,

    It is recommended to use Xamarin.Essentials: File Picker to implement this feature.

    This function is mainly divided into two parts: opening a text file and reading the contents of the file.

    For opening a text file, you could refer to the following code sample:

       var customFileType =  
       new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>  
       {  
               { DevicePlatform.Android, new[] { "text/plain" } },  
       });  
           var options = new PickOptions  
           {  
               PickerTitle = "Please select a text file",  
               FileTypes = customFileType,  
           };  
           var result = await FilePicker.PickAsync(options);  
    

    Then, you could read the content from this text file via the following code:

       if (result != null && result.FileName.EndsWith("txt", StringComparison.OrdinalIgnoreCase))  
       {  
               var content = System.IO.File.ReadAllText(result.FullPath);  
               label.Text = content;  
       }  
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.