Cannot create files on Android with Xamarin

后端 未结 5 911
春和景丽
春和景丽 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: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

提交回复
热议问题