Share via

Xamarin iOS How to File.ReadAllBytes a file inside /private/var/mobile/Containers/Shared/AppGroup/

Jimmy Oku 0 Reputation points
Oct 19, 2024, 2:14 AM
string filePath = "/private/var/mobile/Containers/Shared/AppGroup/7E6455EB-2EF9-417E-BC79-71BA25B53853/File Provider Storage/file.pdf"

byte[] byteFile = File.ReadAllBytes(filePath);

When I run the code above on Xamarin iOS I get an unauthorized exception. Saying access to filePath is denied. Can someone please help me with this, I ran out of ideas at this point.

I added all the permissions below even created App Groups in Xcode and called it in Visual Studio Mac still I'm getting the same error message.

Screenshot 2024-10-18 at 20.08.59

Please help me, I'm running out of time.

Thank you!

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,362 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,063 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jimmy Oku 0 Reputation points
    Oct 21, 2024, 12:35 AM

    The answer is you simply need to call e.Url.StartAccessingSecurityScopedResource();

    Then call e.Url.StopAccessingSecurityScopedResource(); when done

    private void DocumentPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs e)
    {
        var documentUrl = e.Url;
        // Check if the document can be accessed (sandbox security)
        bool isSecured = documentUrl.StartAccessingSecurityScopedResource();
        if (isSecured)
        {
            // Access the document here
           // Once done, release the resource
            documentUrl.StopAccessingSecurityScopedResource();
        }
        else
        {
            // Handle permission denial or failure to access
            Console.WriteLine("Could not access the document.");
        }
    }
    
    0 comments No comments

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.