Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filenames without path of a specific directory

Tags:

c#

.net

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

like image 460
Kottan Avatar asked Jul 25 '11 14:07

Kottan


People also ask

How do I get the full path of a filename?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).

How do I get only the filename from ls?

If you want the ls command output to only contain file/directory names and their respective sizes, then you can do that using the -h option in combination with -l/-s command line option.

How do I get only the filenames in Unix?

If you want to display only the filename, you can use basename command. find infa/bdm/server/source/path -type f -iname "source_fname_*. txt" Shell command to find the latest file name in the command task!


1 Answers

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

like image 147
Vasea Avatar answered Sep 29 '22 02:09

Vasea