Home > Enterprise >  C# not reading files properly when using .Path class
C# not reading files properly when using .Path class

Time:10-17

I'm trying to read a folder and do a look at the file names. Using this code:

  try
  {
    var folderPath = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";

    foreach (string file in Directory.EnumerateFiles(Path.GetFileName(folderPath)))
     {
       var ha = file;
     }
    }
    catch (Exception ex)
     {
       Console.WriteLine(ex);
       Console.ReadLine();
     }

Unfortunately, I'm getting the following error:

The path is not of a legal form

My original filepath:

var folderPath = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";

To find the bad chars I wrote this bit of code:

string illegal = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";
string invalid = new string(Path.GetInvalidFileNameChars())   new string(Path.GetInvalidPathChars());

foreach (char c in invalid)
{
  illegal = illegal.Replace(c.ToString(), "");
}

which came back with:

"CUsersGamersourcereposcarValLocalcarValLocalfiles"

Which clearly isn't a file name.

If I don't use the Path class, it still finds files. How can I make this work because everything I've tried (like removing illegal chars) just doesn't work.

CodePudding user response:

Well, for given folder path

var folderPath = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";

The existing call

Path.GetFileName(folderPath);

returns empty string: "" since

C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\
\                                                        /|
 --------------------- directory ------------------------ file

if you want to look for files in C:\Users\Gamer\source\repos\carValLocal\carValLocal\files you can use Path.GetDirectoryName:

foreach (string file in Directory.EnumerateFiles(Path.GetDirectoryName(folderPath)))
{
    ...
}

If you want some kind of path manipulation, try DirectoryInfo, e.g. let's have a look for files in

  C:\Users\Gamer\source\repos\carValLocal\carValLocal

Code:

  var folderPath = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";

  DirectoryInfo di = new DirectoryInfo(folderPath);

  foreach (string file in Directory.EnumerateFiles(di.Parent.FullName)) {
    ...
  }
  • Related