Get filenames without path of a specific directory

C#.Net

C# Problem Overview


How can I get all filenames of a directory (and its subdirectorys) without the full path? Directory.GetFiles(...) returns always the full path!

C# Solutions


Solution 1 - C#

You can extract the filename from full path.

.NET 3, filenames only
var filenames3 = Directory
				.GetFiles(dirPath, "*", SearchOption.AllDirectories)
				.Select(f => Path.GetFileName(f));
.NET 4, filenames only
var filenames4 = Directory
				.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)
				.Select(Path.GetFileName); // <-- note you can shorten the lambda
Return filenames with relative path inside the directory
// - file1.txt
// - file2.txt
// - subfolder1/file3.txt
// - subfolder2/file4.txt

var skipDirectory = dirPath.Length;
// because we don't want it to be prefixed by a slash
// if dirPath like "C:\MyFolder", rather than "C:\MyFolder\"
if(!dirPath.EndsWith("" + Path.DirectorySeparatorChar)) skipDirectory++;

var filenames4s = Directory
				.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)
				.Select(f => f.Substring(skipDirectory));
confirm in LinqPad...
filenames3.SequenceEqual(filenames4).Dump(".NET 3 and 4 methods are the same?");

filenames3.Dump(".NET 3 Variant");
filenames4.Dump(".NET 4 Variant");
filenames4s.Dump(".NET 4, subfolders Variant");

Note that the *Files(dir, pattern, behavior) methods can be simplified to non-recursive *Files(dir) variants if subfolders aren't important

Solution 2 - C#

See Path.GetFileName:

> Returns the file name and extension of the specified path string.

The Path Class has several useful filename and path methods.

Solution 3 - C#

You want Path.GetFileName

This returns just the filename (with extension).

If you want just the name without the extension then use Path.GetFileNameWithoutExtension

Solution 4 - C#

You can just extract the file name from the full path.

var sections = fullPath.Split('\\');
var fileName = sections[sections.Length - 1];

Solution 5 - C#

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
path, result);

Solution 6 - C#

Although several right answers are there for this questions, You may find this solution as:

string[] files = Directory.EnumerateFiles("C:\Something", "*.*")
                 .Select(p => Path.GetFileName(p))
                 .Where(s => s.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)).ToArray();

Thanks

Solution 7 - C#

Create a DirectoryInfo object, use a search pattern to enumerate, then treat it like an array.

string filePath = "c:\Public\";
DirectoryInfo apple = new DirectoryInfo(@filepath);
foreach (var file in apple.GetFiles("*")
{
   //do the thing
   Console.WriteLine(file)
}

Solution 8 - C#

You can get the files name of particular directory using GetFiles() method of the DirectoryInfo class. Here are sample example to list out all file and it's details of particular directory

System.Text.StringBuilder objSB = new System.Text.StringBuilder();
    System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo("d:\\");
    objSB.Append("<table>");
    objSB.Append("<tr><td>FileName</td>" + 
                 "<td>Last Access</td>" + 
                 "<td>Last Write</td>" + 
                 "<td>Attributes</td>" + 
                 "<td>Length(Byte)</td><td>Extension</td></tr>");

    foreach (System.IO.FileInfo objFile in directory.GetFiles("*.*"))
    {
        objSB.Append("<tr>");

        objSB.Append("<td>");
        objSB.Append(objFile.Name);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.LastAccessTime);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.LastWriteTime);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.Attributes);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.Length);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.Extension);
        objSB.Append("</td>");
       
        objSB.Append("</tr>");
    }
    objSB.Append("</table>");

    Response.Write(objSB.ToString());

This example display list of file in HTML table structure.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKottanView Question on Stackoverflow
Solution 1 - C#VaseaView Answer on Stackoverflow
Solution 2 - C#Mitch WheatView Answer on Stackoverflow
Solution 3 - C#ChrisFView Answer on Stackoverflow
Solution 4 - C#Matt GrandeView Answer on Stackoverflow
Solution 5 - C#Santosh KokatnurView Answer on Stackoverflow
Solution 6 - C#DevView Answer on Stackoverflow
Solution 7 - C#Josh GarciaView Answer on Stackoverflow
Solution 8 - C#Jayesh SorathiaView Answer on Stackoverflow