Using GetFiles but splitting the results to show full path and just the filename

724 views Asked by At

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.

3

There are 3 answers

1
Tim Schmelter On BEST ANSWER

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();
0
Sergey Berezovskiy On

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
            };
0
manish On
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);
}