无法使用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屋!