Saving a file to anywhere public

Hello, new user of Xamarin here - please be gentle.

I know I am missing something here... I simply don't understand what...
I want to save a file - any file to any location on my android device that I can access.

I am using this code to get the location I want to save to:
var my_dir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
Debug.WriteLine($"Folder is {my_dir}");
When I run this code, I get the location as "/data/user/0/com.companyname.PIRtool/files" which I am not able to access.
I have read countless number of forums that say another option is to use something like this:
var my_dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);
Now this code won't work as I get "Error CS0103 The name 'Android' does not exist in the current context"
This suggests to me I am putting it in the wrong place.

2 questions. Where would I put this piece of code and how can I call it from the main code (my c# code)

Appreciate any direction anyone can give me - before I pull my hair out :-)

Thanks
Steve

Tagged:

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    /data/user/0/com.companyname.PIRtool/files this path, you can save the file to your application directory

    /storage/emulated/0/Documents you can save the file to the public documents directory like following screenshot.

    Note if you store the File in the your application directory, because in android 10.0 or later, by default. Such apps can see only their app-specific directory, If you want to stick With What Worked Before. For Android Q ,you could try to add android:requestLegacyExternalStorage="true" to your <application> element in the manifest.

    https://developer.android.google.cn/training/data-storage/files/external-scoped

    I did not know about your "access the file", do you want to find this file in android device Or the DDMS?
    If you want to access file in the DDMS, you can save the path, both of them are Ok.
    If you want to access the file in the android device, I advice you to use the Seond way to achieve that.

    In the end, do not forget to request two persmission in your application

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    "Error CS0103 The name 'Android' does not exist in the current context"

    I don't know where you put the code to run. Can you share a demo?

    questions. Where would I put this piece of code and how can I call it from the main code (my c# code)

    I test above code, I put both of them to Activity or Class method, all is Ok. If you still confused, you can share your demo.

Sign In or Register to comment.