首页 > 解决方案 > 如何从目录符号链接中获取文件

问题描述

我尝试从目录符号链接中获取路径列表。这是写异常

找不到路径的一部分。

var filePath = @"C:\symlink";

var paths = new List<string>((Directory
  .GetFiles(filePath, "*.*", SearchOption.AllDirectories))
  .OrderBy(x => new FileInfo(x).Name));

标签: c#file

解决方案


您必须检查目录是否存在;例如,如果我们想在目录不存在时获得一个空列表

var filePath = @"C:\symlink";

var paths = Directory.Exists(filePath)
  ? Directory
      .EnumerateFiles(filePath, "*.*", SearchOption.AllDirectories)
      .OrderBy(file => Path.GetFileName(file))
      .ToList()
  : new List<string>();  

请注意,我们不必使用which 将所有文件GetFiles(...)读取到一个数组中,而是可以使用枚举文件EnumerateFiles


推荐阅读