c# - Directory.GetDirectories 抛出异常

标签 c# path

在下面的代码中,我有两个变量,一个是currentDirectoryPath,另一个是rootPath。我想使用 Directory.GetDirectories() 函数枚举这两个根路径中的所有子文件夹。但是,当我传递 currentDirectoryPath 时,代码工作正常,但不适用于 rootPath。抛出异常:

NotSupportedException: The given path's format is not supported.

我已经用两个路径测试了代码:

 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;

   namespace ConsoleApp
   {
       class Program
       {
           static void Main(string[] args)
           {
               string currentDirectoryPath = Directory.GetCurrentDirectory();
               string rootPath = "‪C:\\Users\\Ravi.Reddy\\Desktop\\Practise";

               string[] dirs1 = Directory.GetDirectories(
                   currentDirectoryPath, 
                  "*.*", 
                   SearchOption.AllDirectories);

              foreach (var dir in dirs1)
                  Console.WriteLine(dir);

              string[] dirs2 = Directory.GetDirectories( // <- Exception here
                  rootPath, 
                 "*.*",
                  SearchOption.AllDirectories);

              foreach (var dir in dirs2)
                  Console.WriteLine(dir);

              Console.ReadLine();
           }
      }
 }

我希望 Directory.GetDirectories() 应该使用提供的路径,并且它应该枚举所有子文件夹。

最佳答案

您的不正确rootPath ,看看潮湿:

  using System.Linq;

  ...

  // Copy + Paste from the question
  string rootPath = "‪C:\\Users\\Ravi.Reddy\\Desktop\\Practise";

  Console.Write(string.Join(Environment.NewLine, 
    rootPath.Select(c => $"\\u{(int)c:x4} : {c}")));

结果:

\u202a : ‪
\u0043 : C
\u003a : :
\u005c : \
\u0055 : U
\u0073 : s
\u0065 : e
\u0072 : r
\u0073 : s
 ... 

请注意\u202a字符码 ( LEFT-TO-RIGHT EMBEDDING ) 它不得出现在有效路径中。您所要做的就是重新输入 "‪C:片段以消除不可见 LEFT-TO-RIGHT EMBEDDING 符号。

关于c# - Directory.GetDirectories 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56472909/

相关文章:

python - R: system() 不能使用 .bashrc 中定义的 bash 函数

python - 从给定的路径列表中获取文件夹的结构作为字符串

java - 绘制矩形或椭圆时,Path.Direction.CCW 和 CW 有什么区别?

android - 如何在ubuntu 12.04中设置Android SDK、NDK和JDK路径

c++ - 我应该把这个 .h 文件放在哪里,或者我怎样才能在 TextMate 中正确设置我的路径?

c# - 将逗号分隔的数据集拆分为单独的数组

C# - Webclient 发布数据问题

C# 从泛型基类中的字段反射 GetValue

javascript - 如何根据其他两个带有数值的文本框验证文本框(总计)

c# - ASP.Net LinkBut​​ton 在本地工作但不能在服务器上工作