【问题标题】:winrt how to get files list from device using c#winrt如何使用c#从设备获取文件列表
【发布时间】:2015-05-26 15:01:03
【问题描述】:

我需要在我的通用应用程序中获取设备(手机或 PC)中所有文件的列表。在 wpf 我做了一些这样的事情:

class Collection {
    private StringCollection seachResults; 
    //find all mp3 files in local storage
    private void ScanDrives() {
        seachResults.Clear();
        string[] drives = Environment.GetLogicalDrives();
        foreach (string dr in drives) {
            DriveInfo di = new DriveInfo(dr);
            if (!di.IsReady) {
                //skip if drive not ready
                continue;
            }
            DirectoryInfo rootDir = di.RootDirectory;
            WalkDirectoryTree(rootDir);
        }
    }

    private void WalkDirectoryTree(DirectoryInfo root) {
        FileInfo[] files = null;
        DirectoryInfo[] subDirs = null;
        try {
            files = root.GetFiles("*.mp3");
        } catch (UnauthorizedAccessException e) {

        } catch (DirectoryNotFoundException e) {

        }

        if (files != null) {
            foreach (FileInfo fileInfo in files) {
                seachResults.Add(fileInfo.FullName);
            }
            subDirs = root.GetDirectories();
            foreach (DirectoryInfo dirInfo in subDirs) {
                WalkDirectoryTree(dirInfo);
            }
        }
    }
}

但是当我尝试将其迁移到 winRT 应用程序时,我收到了一些错误,例如 unknown type Driveunexisted method Environment.GetLogicalDrives()

谁能说在winRT中是怎么做到的?

【问题讨论】:

  • Environment.GetLogicalDrives();我相信只适用于win32或win64。你试过 System.IO 的 GetLogicalDrives() 吗?

标签: c# .net windows-runtime system.io.file


【解决方案1】:

您不会找到在 WinRT 应用程序中获取所有逻辑驱动器的方法; WinRT 应用程序存在于沙盒环境中,并且如果在应用程序清单中声明为一项功能,则只能访问它们自己的隔离存储或已知文件夹(如音乐)。

例如,要访问用户的音乐文件夹,您可以这样做(不要忘记在应用清单中声明该功能):

StorageFolder folder = Windows.Storage.KnownFolders.MusicLibrary;

访问文件系统任何其他部分的唯一方法是用户通过文件选择器明确授予访问权限:

var folderPicker = new FolderPicker();
var folder = await folderPicker.PickSingleFolderAsync();

【讨论】:

  • 谢谢。您能告诉我媒体文件是否存储在闪存中,它们是否会自动添加到音乐库中(如果设备是手机)?
  • 是的,KnownFolders.MusicLibrary 返回的 StorageFolder 是一个虚拟文件夹,查询它会返回存储在内部和可移动存储上的文件。如果由于某种原因,您需要访问的音乐文件不在 SD 卡上的标准音乐文件夹之外,那么您可以访问 SD 卡 - msdn.microsoft.com/en-us/library/windows/apps/xaml/… - 但如果音乐是存放在正确的地方。
  • 谢谢。这就是我所需要的。
【解决方案2】:

你试过System.IO.Directory.GetLogicalDrives()吗?

我相信 Environment.GetLogicalDrives() 仅适用于 Win32/Win64。如果我没记错的话,System.IO.Directory 存在于 mscorlib 中,并且可以在 Phone、RT 或 Regular 版本中广泛使用。

MSDN 参考资料:

https://msdn.microsoft.com/en-us/library/system.io.directory.getlogicaldrives%28v=vs.110%29.aspx

【讨论】:

  • 我收到错误“System.IO 命名空间中不存在目录”。项目类型是可移植类库。我读到在 winRT 中存在 Windows.Storage.Folder 而不是 System.IO.Directory 但它没有获取逻辑驱动程序的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2011-05-01
相关资源
最近更新 更多