无法使用 Xamarin 在 Android 上创建文件 [英] Cannot create files on Android with Xamarin
问题描述
我有一个适用于 Android 的 Xamarin-Studio 应用程序,我只想下载文件并将它们保存在本地.但是,当我尝试在 files
文件夹中创建文件时,出现异常:
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 exception:
File.Create("data/data/com.company.app/files/newFile.png");
给我:
System.UnauthorizedAccessException
Access to the path 'data/data/com.company.app/files/newFile.png' is denied.
我做错了什么?
推荐答案
我终于意识到 File.create()
不是问题所在.我有这样的代码:
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 ();
然而,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 ();
在我的辩护中,FileExistsAndIsDirectory
异常比 UnauthorizedAccessException
异常更有帮助
In my defense, an FileExistsAndIsDirectory
exception would have been much more helpful than the UnauthorizedAccessException
这篇关于无法使用 Xamarin 在 Android 上创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!