Cannot create files on Android with Xamarin

后端 未结 5 906
春和景丽
春和景丽 2020-12-19 00:38

I have a Xamarin-Studio App for Android and I simply want to download files and save them locally. But when I try to create a file in the files folder I get an

相关标签:
5条回答
  • 2020-12-19 01:20

    Using Mono, I think must be the same as in Xamarin Studio.

    var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    File.Create(path + "newFile.png");
    
    0 讨论(0)
  • 2020-12-19 01:22

    Add the following permission to Android.Manifest file

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

    0 讨论(0)
  • 2020-12-19 01:34

    I finally realized that File.create() was not the problem. I had code like this:

    string tmpFilePath = FilesDir.AbsolutePath.stringByAppendingPath (f.Path);
    Java.IO.File tmpFile = new Java.IO.File( tmpFilePath);
    tmpFile.Mkdirs ();
    

    Yet, Mkdirs() does not only create all intermediate directories – as I had assumed – but also creates a directory at the file path itself. So the file could not be created because there already was a directory with the same name. The correct way is:

    string tmpFile = FilesDir.AbsolutePath.stringByAppendingPath (f.Path);
    Java.IO.File tmpParentFolder = new Java.IO.File(tmpFile).getParentFile();
    tmpParentFolder.Mkdirs ();
    

    In my defense, an FileExistsAndIsDirectory exception would have been much more helpful than the UnauthorizedAccessException

    0 讨论(0)
  • 2020-12-19 01:37

    You should use Environment or IsolatedStorage. For example:

    var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    var filename = Path.Combine(path, "newFile.png");
    
    0 讨论(0)
  • 2020-12-19 01:39

    I am coding Xamarin with VS2013. I had the access denied error for a directory created with the application I am writing. My application creates a directory called /storage/emulated/0/POIApp by concatenating via:

    System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, "POIApp");
    

    I found that I had to use VS2013 to edit the "properties" of my application (POIApp), i.e., right-click the project icon in the solution explorer; choose properties from the pop-up menu. A new tab appears in the main VS2013 window. On the left there are a few choices, e.g., Application, Android Manifest, Android Options, Build, etc. Choose "Android Manifest". At the bottom of the main panel is a section "required permissions". My problem was solved when I checked "READ_EXTERNAL_STORAGE" and "WRITE_EXTERNAL_STORAGE".

    0 讨论(0)
提交回复
热议问题