我正在尝试从 Android 手机上的文件夹中获取项目。
但是,FolderBrowserDialog 不允许我从手机中选择文件夹。路径如下所示 This PC\Xperia Z3 Compact\SD Card\Music
要选择我当前正在使用的文件夹:
private void button_Click(object sender, EventArgs e)
{
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
UserFolderLocation = dlg.SelectedPath;
}
else { }
}
然后在搜索文件夹中的内容时,我使用:
try
{
folderItems = Directory.GetFiles(directory).Select(f => Path.GetFileNameWithoutExtension(f)).ToArray();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
如果我插入路径 This PC\Xperia Z3 Compact\SD Card\Music
作为变量然后搜索它,它会抛出 System.IO.DirectoryNotFoundException
。
如何选择和使用不是以 c:
、d:
等开头的路径?
最佳答案
最后我最终使用了 shell32 库。它能够处理可移植设备(包括和不包括驱动器号)。
包括对 shell32.dll
的引用
并包含库:
using Shell32;
然后我没有使用 FolderBrowserDialog,而是使用 shell 浏览文件夹。它为手机上的文件夹返回一个奇怪的路径,因为我用来测试路径的手机看起来像这样:
::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\?\usb#vid_04e8&pid_6860&ms_comp_mtp&samsung_android#6&fee689d&3&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\SID-{20002,SECZ9519043CHOHB01,63829639168}\{ 013C00D0-011B-0130-3A01-380113012901}
public int Hwnd { get; private set; }
private void button3_Click(object sender, EventArgs e)
{
Shell shell = new Shell();
Folder folder = shell.BrowseForFolder((int)Hwnd, "Choose Folder", 0, 0);
if (folder == null)
{
// User cancelled
}
else
{
FolderItem fi = (folder as Folder3).Self;
UserFolderLocation = fi.Path;
}
}
然后选择搜索文件夹中的内容:
try
{
Folder dir = shell.NameSpace(directory);
List<string> list = new List<string>();
foreach (FolderItem curr in dir.Items())
{
list.Add(curr.Name);
}
folderItems = list.ToArray();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
关于c# - 无法从外部设备获取目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33331667/