C# return full path with GetFiles

user1775334 picture user1775334 · Mar 18, 2013 · Viewed 25.8k times · Source

Use this code for search files in directory:

FileInfo[] files = null;
string path = some_path;
DirectoryInfo folder = new DirectoryInfo(path);
files = folder.GetFiles("*.*", SearchOption.AllDirectories);

This return only filename and extension (text.exe). How to return full path to file(C:\bla\bla\bla\text.exe)?

If I use Directory.GetFiles("*.*"), this return full path. But if folder contains point in name(C:\bla\bla\test.0.1), result contains path to folder without file:

  • 0 C:\bla\bla\bla\text.exe
  • 1 C:\bla\bla\test.0.1
  • 2 C:\bla\text.exe

etc.

Answer

Ilya Ivanov picture Ilya Ivanov · Mar 18, 2013

FileInfo contains a FullName property, which you can use to retrieve full path to a file

var fullNames = files.Select(file => file.FullName).ToArray();

Check

This code on my machine:

FileInfo[] files = null;
string path = @"C:\temp";
DirectoryInfo folder = new DirectoryInfo(path);
files = folder.GetFiles("*.*", SearchOption.AllDirectories);

//you need string from FileInfo to denote full path
IEnumerable<string> fullNames = files.Select(file => file.FullName);

Console.WriteLine ( string.Join(Environment.NewLine, fullNames ) );

prints

C:\temp\1.dot 
C:\temp\1.jpg 
C:\temp\1.png 
C:\temp\1.txt 
C:\temp\2.png 
C:\temp\a.xml 
...

Full solution

The solution to your problem might look like this:

string path = @"C:\temp";
DirectoryInfo folder = new DirectoryInfo(path);
var directories = folder.GetDirectories("*.*", SearchOption.AllDirectories);


IEnumerable<string> directoriesWithDot = 
 directories.Where(dir => dir.Name.Contains("."))
            .Select(dir => dir.FullName);


IEnumerable<string> filesInDirectoriesWithoutDot = 
 directories.Where(dir => !dir.Name.Contains("."))
            .SelectMany(dir => dir.GetFiles("*.*", SearchOption.TopDirectoryOnly))
            .Select(file => file.FullName);


Console.WriteLine ( string.Join(Environment.NewLine, directoriesWithDot.Union(filesInDirectoriesWithoutDot) ) );