0

I am using “GetFiles” to extract files in a specified folder as shown below:

Directory.GetFiles(_dirPath, File_Filter);

This creates a string array which is fine but now I need to do something similar but create a Tuple array where each Tuple holds the full path including filename and also just the filename. So at the moment I have this in my string

C:\temp\test.txt

The new code needs to create a Tuple where each one looks similar to this:

Item1 = C:\temp\test.txt
Item2 = test.txt

I’m guessing I could do this this with a bit of Linq but am not sure. Speed and efficiency is too much of a problem as the lists will be very small.

Retrocoder
  • 4,483
  • 11
  • 46
  • 72

3 Answers3

5

You should use Directory.EnumerateFiles with LINQ which can improve performance if you don't need to consume all files. Then use the Path class:

Tuple<string, string>[] result = Directory.EnumerateFiles(_dirPath, File_Filter)
    .Select(fn => Tuple.Create( fn, Path.GetFileName(fn) ))
    .ToArray();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Use DirectoryInfo.GetFiles to return FileInfo instances, which have both file name and full name:

var directory = new DirectoryInfo(_dirPath);
var files = directory.GetFiles(File_Filter);

foreach(var file in files)
{
    // use file.FullName
    // use file.Name
}

That's much more readable than having tuple.Item1 and tuple.Item2. Or at least use some anonymous type instead of tuple, if you don't need to pass this data between methods:

var files = from f in Directory.EnumerateFiles(_dirPath, File_Filter)
            select new {
                Name = Path.GetFileName(f),
                FullName = f
            };
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
-1
string[] arrayOfFiles = Directory.GetFiles(PathName.Text); // PathName contains the Path to your folder containing files//
string fullFilePath = "";
string fileName = "";
foreach (var file in arrayOfFiles)
{
    fullFilePath = file;
    fileName = System.IO.Path.GetFileName(file);
}
manish
  • 1,450
  • 8
  • 13