How can i copy file from my app's resources to device's default Documents folder?

I need to copy few .pdf documents to "Documents" folder of device, so user can open this file later with any program and find it in explorer.
Also it would be nice to open it in default program to view .pdf files on device(something like URI could be nice).

All i have for now is one of the document's in app's folder.
My project is Xamarin.Forms Shared.

Best Answer

Answers

  • VolodymyrSavchenkoVolodymyrSavchenko UAMember ✭✭✭

    Thanks, but could this work with Shared project?
    Also i need to copy file to device's "Documents" folder. Not to SD card, because some devices don't have it.

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    This is android version . Yes, you can use it I a PCL project via dependency service or in a shared project: I see no problems. For documents folder take a look to android api how is defined "document"

  • YkshLeoYkshLeo USMember ✭✭✭✭

    Just have a look at this, It can help you :smile:

    private void copyAssets() {
        AssetManager assetManager = getAssets();
        String[] files = null;
        try {
            files = assetManager.list("");
        }
        catch (IOException e) {
            Log.e("tag", "Failed to get asset file list.", e);
        }
        if (files != null) for (String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = assetManager.open(filename);
                File outFile = new File(getExternalFilesDir(null), filename);
                out = new FileOutputStream(outFile);
                copyFile(in, out);
            }
            catch(IOException e) {
                Log.e("tag", "Failed to copy asset file: " + filename, e);
            }     
            finally {
                if (in != null) {
                    try {
                        in.close();
                    }
                    catch (IOException e) {
                        // NOOP
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    }
                    catch (IOException e) {
                        // NOOP
                    }
                }
            }  
            }
    }
    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
          out.write(buffer, 0, read);
        }
    }
    

    Reference :

Sign In or Register to comment.