编辑:我做了一些研究,对我的问题很重要:
我使用Intent对象从用户获取文件路径。他使用了一些随机文件浏览器。我安装到模拟器的那个返回路径如下:
fileName =“file:///mnt/sdcard/Alien/PlayersBase.btb”
这不起作用。
如果我以编程方式访问同一个文件,知道文件在哪里,我会这样做:
string str = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "Alien/PlayersBase.btb");
现在
str =“/ mnt / sdcard / Alien / PictersBase.btb”
第二条路径不同,效果很好。
所以我的问题应该更像是这样:我期望Intent对象返回什么以及为什么我在google上找到的第一个文件浏览器返回的字符串会返回不起作用的东西?
问题的第一个版本
我的目标是允许用户在android中选择一个文件,我想将此文件复制到我的应用程序的本地文件夹中。
从this question我采取了第三个答案,允许用户在三星和非三星设备上选择文件。 下面的代码似乎工作正常,android让我选择我想要使用哪个资源管理器,我可以浏览并选择文件。为了完整,我在这里发布代码:
Activity mainActivity = context as Activity;
string minmeType="*/*";
Intent intent = new Intent(Intent.ActionGetContent);
intent.SetType(minmeType);
intent.AddCategory(Intent.CategoryOpenable);
//special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.PutExtra("CONTENT_TYPE", minmeType);
sIntent.AddCategory(Intent.CategoryDefault);
Intent chooserIntent;
if (mainActivity.PackageManager.ResolveActivity(sIntent, 0) != null)
{
// it is device with samsung file manager
chooserIntent = Intent.CreateChooser(sIntent, "Open file");
chooserIntent.PutExtra(Intent.ExtraInitialIntents, new Intent[] { intent });
}
else
{
chooserIntent = Intent.CreateChooser(intent, "Open file");
}
try
{
mainActivity.StartActivityForResult(intent, 3);
}
catch
{
SendMessageToUser("No suitable File Manager was found.");
}
然后我将此代码放入我的活动
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode==3 && resultCode == Result.Ok) //pick file
OnFileSelected(data.DataString);
}
我尝试使用此处的文件
public void OnFileSelected(string fileName)
{
try
{
Stream streamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read);
...
}
catch (Exception e)
{
string message = e.ToString();
}
}
初始化streamSource会引发异常:
fileName =“file:///mnt/sdcard/Alien/PlayersBase.btb”
,例外是
“System.IO.DirectoryNotFoundException:找不到路径的一部分”/file:///mnt/sdcard/Alien/PlayersBase.btb“............... ..“
我会理解,如果我没有某些文件夹的权限,但为什么它说文件浏览器中选择的确切文件不存在?