Search code examples
filexamarinlocal

How to open local file in browser using xamarin?


Im using xamarin and i want to open a local file (txt or pdf) in a browser directly frol the app.

So i do this :

 var uri = new System.Uri(path, UriKind.Absolute);
 await Browser.OpenAsync(uri, BrowserLaunchMode.SystemPreferred);

And I have the following exception :

System.ArgumentException : 'IDN labels must be between 1 and 63 characters long.

I think it's possible but i dont know how to do.


Solution

  • I don't think you can open a local file (txt or pdf) in a browser directly from the app. The file is stored in your local path(not a web link) and the browser is not able to open it.

    You can use Xamarin.Essentials: Launcher to open a file in your app:

    This features enables an app to request other apps to open and view a file. Xamarin.Essentials will automatically detect the file type (MIME) and request the file to be opened.

    The code example is :

    var fn = "File.txt";
    var file = Path.Combine(FileSystem.CacheDirectory, fn);
    File.WriteAllText(file, "Hello World");
    
    await Launcher.OpenAsync(new OpenFileRequest
    {
        File = new ReadOnlyFile(file)
    });
    

    If you want to open a web link with the browser, you can use Xamarin.Essentials: Browser.