Search code examples
filexamarin.formsandroid-external-storage

Xamrin Forms: How to read the details of a file stored in device's external storage?


I have implemented creating a folder and file in the device's external storage and writing data into that file using this thread.

Now I am trying to get the details of the file. For that, I have added a new function in the interface like below.

//Interface
public interface IAccessFile
{
    void CreateFile(string text);
    Java.IO.File GetFileDetails();
}

//Android implementation
public Java.IO.File GetFileDetails()
{
    string rootPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
    var filePathDir = Path.Combine(rootPath, "StockPDT");
    if (File.Exists(filePathDir))
    {
        string filePath = Path.Combine(filePathDir, "STOCK.TXT");
        Java.IO.File file = new Java.IO.File(filePath);
        return file;
    }
    else
    {
        return null;
    }
}

But the problem is with the interface function part, getting below error":

The type or namespace name 'Java' could not be found (are you missing a using directive or an assembly reference?)

Screenshot:

enter image description here

If I return the file from the android part like above, it is easy to get the file details in the portable project. Instead of File, I try to return the file path, but it is empty. Is there any other way to get the file details other than this?


Solution

  • As per the notes in question, I tried to fetch the file details using its path.

    Reference: https://learn.microsoft.com/en-us/answers/questions/319908/xamrin-forms-how-to-read-the-details-of-a-file-sto.html

    //Interface
    public interface IAccessFile
    {
        string GetFileDetails();
    }
    
    //Android implementation
    public string GetFileDetails()
    {
        string rootPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
        var filePathDir = Path.Combine(rootPath, "StockPDT");
        if (!File.Exists(filePathDir))
        {
            Directory.CreateDirectory(filePathDir);
        }
        string filePath = Path.Combine(filePathDir, "STOCK.TXT");
        return filePath;
    }
    
    //Main Project:
    string path = DependencyService.Get<IAccessFile>().GetFileDetails();
    string fileDetails = File.ReadAllText(path);