c# - 无法从外部设备获取目录

标签 c#

我正在尝试从 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/

相关文章:

c# - 用于多平台大型软件开发的编程语言?

c# - .NET 3.5 列表框选定值 (Winforms)

c# - 列表的排序包含具有字母/数字的字符串

c# - 反序列化数组内的数组

c# - 绑定(bind)到 SqlDataAdapter 后,ASP.NET GridView 宽度不会保持在 100%

c# - 如何将 ViewModel 属性绑定(bind)到转换器中的依赖属性

c# - 加密字符串在 ASP.NET MVC 中产生 404 错误

c# - 获取方法还是私有(private)属性(property)?

c# - 如何在 Visual C# 中制作 Windows 95 风格的按钮?

c# - c#动态添加对象属性