简体   繁体   中英

Directory.GetDirectories throwing exception

In the below code I have two variable one is currentDirectoryPath and the other is rootPath . I want to enumerate all the subfolders in these two root paths using Directory.GetDirectories() function. But when I pass currentDirectoryPath the code is working fine but not with the rootPath. I have an exception thrown :

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

I have tested the code with the two paths:

 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();
           }
      }
 }

I expect Directory.GetDirectories() should work with the provided path and it should enumerate all the subfolders.

You have an incorrect rootPath , just have a look at the damp :

  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}")));

Outcome:

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

Please, note \‪ charcode ( LEFT-TO-RIGHT EMBEDDING ) It must not appear in a valid path. All you have to do is to retype "‪C: fragment in order to get rid of invisible LEFT-TO-RIGHT EMBEDDING symbol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM