简体   繁体   中英

Access denied error on Saving PDF data to documents directory in Xamarin iOS

I am having an app in which I am trying to share PDF file from my iOS device. So I am opening UIDocumentPickerViewController on my button click.

On selecting any PDF file from my device, I am trying to save it to documents directory and then send it to server.

I am successfully able to get the URL and when I try to save it to the documents folder, it gives me and error saying "Access Denied".

I have searched a lot but could not find a solution.

Below is my code.

private void UI_DidPickDocumentAtUrls(object sender, UIDocumentPickedAtUrlsEventArgs e)
{
     storePDFData(e.Urls[0]);
}
    
    
private void storePDFData(NSUrl dataUrl)
{
    var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var directory = Path.Combine(documents, "Pdfs");
    if (!File.Exists(directory))
    {
        Directory.CreateDirectory(directory);
    }
    Console.WriteLine(dataUrl.LastPathComponent);
    
    var filename = Path.Combine(directory, dataUrl.LastPathComponent);
    dataUrl.StartAccessingSecurityScopedResource();
    FileStream fs = new FileStream(dataUrl.Path, FileMode.Open, FileAccess.ReadWrite);
    StreamReader reader = new StreamReader(fs);
    string content = reader.ReadToEnd();
    //byte[] content = File.ReadAllBytes(dataUrl.Path);
    if (content != null)
    {
        File.WriteAllText("file:///" + filename, content);
    }
    dataUrl.StopAccessingSecurityScopedResource();
}

Any help would be highly appreciated.

Thanks in advance.

The file path file:/// in iOS is invalid, you could try to use filename directly in this scenario.

File.WriteAllText(filename , content);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM