0

Is there a method similar to Directory.EnumerateFiles that will return the relative paths of each file in a directory instead of their absolute paths?

I'm trying to fetch all files from the current directory, the paths will later be used to log into the terminal with some diagnostics. This is how I'm doing it right now, but the issue is that this returns the files with their absolute paths:

var allFiles = Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories);

I could then substring each of them to get their relative paths, but that would require allocating new strings for each path name which is not ideal with the amount of files we have to process. I needed to get the path of the file relative to the current directory so as to not break the formatting of our diagnostics when the absolute path is too large.

We need a way to fetch the relative paths directly instead of their absolute paths.

KTSnowy
  • 29
  • 1
  • 6

2 Answers2

0

Get the absolute path of each file and then use the Path class to get the relative path of each absolute path using the base folder path like in the code below.

var absolutePaths = Directory.GetFiles("./");
//declare a list to hold the relative paths
var relativePaths = new List<string>();
foreach(var file in absolutePaths){
  var relativePath = 
   Path.GetRelativePath("./",file);
  relativePaths.Add(relativePath);
}
if(relativePaths.Count >0){
//TO DO
}
Son of Man
  • 1,213
  • 2
  • 7
  • 27
0

Just map the absolute paths to relative using Path.GetRelativePath:

var dir = Directory.GetCurrentDirectory();
var allFiles = Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)
    .Select(p => Path.GetRelativePath(dir, p));

If you are not on .NET Core 2 or higher, use one of the methods from How to get relative path from absolute path instead of Path.GetRelativePath.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36