Get filenames without path of a specific directory - c#

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

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

See Path.GetFileName:
Returns the file name and extension of the specified path string.
The Path Class has several useful filename and path methods.

You want Path.GetFileName
This returns just the filename (with extension).
If you want just the name without the extension then use Path.GetFileNameWithoutExtension

You can just extract the file name from the full path.
var sections = fullPath.Split('\\');
var fileName = sections[sections.Length - 1];

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);

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

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)
}

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.

Related

Adding File and Directory to Array

I have this method that searches all files and folders in "C:\Sharing".
string[] fileArray = Directory.GetFiles(#"C:\Sharing", "*.*", SearchOption.AllDirectories);
And foreach shows me full path of each file. Great. However, since these are in a directory called "Sharing", I want to check and add files that are like
C:\Sharing\Jerry2022\wedding.jpg (array: 'wedding.jpg', 'Jerry2022')
C:\Sharing\snapshot.jpg (array: 'snapshot.jpg')
C:\Sharing\Newsletter\cover-june.webp (array: 'cover-june.webp', 'Newsletter')
So as you can see, I want to add file and subdirectory name to a string array or List, doesnt matter. Excluding "Sharing".
How can I split the results? I know I can use Substring and LastIndexOf("\") + 1 and separate the ending '' but I'm not sure how to match up the filename with the subdir name too.
Any help is appreciated
You can use DirectoryInfo to get the information you want:
C#:
var directoryInfo = new DirectoryInfo(#"C:\Sharing");
if (directoryInfo.Exists)
{
foreach (var fileInfo in directoryInfo.GetFiles("*.*", SearchOption.AllDirectories))
{
var fileName = fileInfo.Name;
Console.WriteLine(fileName);
var directoryName = fileInfo.DirectoryName;
// you can use split to get the directory name array
Console.WriteLine(directoryName);
}
}
I found an other way, use Uri for this scenario:
C#:
string[] fileArray = Directory.GetFiles(#"C:\Sharing", "*.*", SearchOption.AllDirectories);
foreach (var s in fileArray)
{
var uri = new Uri(s);
var uriSegments = uri.Segments.ToArray();
}
You will see each part of the full path, but you may need to use .Trim('/') for each part. Then you can use string.Equals to get directories which you want.
You could split the results using Split
But of course you can also work with FileInfo instead

Move files according to searchPattern

I have excel list with file names that I want to move from one folder to another. And I can not just copy paste the files from one folder to another since there are allot of files that do not match the excel list.
private static void CopyPaste()
{
var pstFileFolder = "C:/Users/chnikos/Desktop/Test/";
//var searchPattern = "HelloWorld.docx"+"Test.docx";
string[] test = { "HelloWorld.docx", "Test.docx" };
var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, test.ToString()))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
}
}
I have tried several things but I still think that with a array it would be the easiest way to do it(correct me if I am wrong).
The issue that I face right now is that it can not find any files (there are files under this name.
You can enumerate the files in the directory by using Directory.EnumerateFiles and use a linq expression to check if the file is contained in you string array.
Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d)));
So your foreach would look like
this
foreach (var file in Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d)))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
Actually no, this will not search the directory for pst files. Either build the path yourself using Path.Combine and then iterate over the string-array, or use your approach. With the code above, you need to update the filter, because it will not find any file when given a string[].ToString (). This should do:
Directory.GetFiles (pstFileFolder, "*.pst")
Alternatively, you can iterate over all files without a filter and compare the filenames to your string-array. For this, a List<string> would be a better way. Just iterate over the files like you're doing and then check if the List contains the file via List.Contains.
foreach (var file in Directory.GetFiles (pstFileFolder))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Here, either iterate over the string array or use a List
if (!nameList.Contains (theFileInfo.Name)) continue;
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
I think you need this
var pstFileFolder = "C:/Users/chnikos/Desktop/Test/";
//var searchPattern = "HelloWorld.docx"+"Test.docx";
string[] test = { "HelloWorld.docx", "Test.docx" };
var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/";
// Searches the directory for *.pst
foreach (var file in test)
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var source = Path.Combine(soruceFolder, theFileInfo.Name);
var destination = Path.Combine(pstFileFolder, file);
if (File.Exists(source))
File.Move(file, destination);
}

c# Directory.GetFiles file structure from app root

I have the following piece of code:
string root = Path.GetDirectoryName(Application.ExecutablePath);
List<string> FullFileList = Directory.GetFiles(root, "*.*",
SearchOption.AllDirectories).Where(name =>
{
return !(name.EndsWith("dmp") || name.EndsWith("jpg"));
}).ToList();
Now this works very well, however the file names with it are quire long.
is there a way i can take out the path till root? but still show all the subfolders?
Root = C:\Users\\Desktop\Test\
But the code would return the whole path from C:
while I'd prefer if I could take out the root bit straight away. but still keep the file structure after it.
eg
C:\Users\\Desktop\Test\hi\hello\files.txt
would return
\hi\hello\files.txt
I know i can just iterate over the file list generated and remove it all one by one, I'm wondering if I can just filter it out stright.
Using the power of LINQ:
string root = Path.GetDirectoryName(Application.ExecutablePath);
List<string> FullFileList = Directory.GetFiles(root, "*.*", SearchOption.AllDirectories)
.Where(name =>
{
return !(name.EndsWith("dmp") || name.EndsWith("jpg"));
})
.Select(file => file.Replace(root, "")
.ToList();

How to get file names from the directory, not the entire path

I am using the below method to get the file names. But it returns the entire path and I don't want to get the entire path. I want only file names, not the entire path.
How can I get that only file names not the entire path
path= c:\docs\doc\backup-23444444.zip
string[] filenames = Directory.GetFiles(targetdirectory,"backup-*.zip");
foreach (string filename in filenames)
{ }
You could use the GetFileName method to extract only the filename without a path:
string filenameWithoutPath = Path.GetFileName(filename);
System.IO.Path is your friend here:
var filenames = from fullFilename
in Directory.EnumerateFiles(targetdirectory,"backup-*.zip")
select Path.GetFileName(fullFilename);
foreach (string filename in filenames)
{
// ...
}
Try GetFileName() method:
Path.GetFileName(filename);
You can use this, it will give you all file's name without Extension
List<string> lstAllFileName = (from itemFile in dir.GetFiles()
select Path.GetFileNameWithoutExtension(itemFile.FullName)).Cast<string>().ToList();
Linq is good
Directory.GetFiles( dir ).Select( f => Path.GetFileName( f ) ).ToArray();

Exclude certain file extensions when getting files from a directory

How to exclude certain file type when getting files from a directory?
I tried
var files = Directory.GetFiles(jobDir);
But it seems that this function can only choose the file types you want to include, not exclude.
You should filter these files yourself, you can write something like this:
var files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml"));
I know, this a old request, but about me it's always important.
if you want exlude a list of file extension: (based on https://stackoverflow.com/a/19961761/1970301)
var exts = new[] { ".mp3", ".jpg" };
public IEnumerable<string> FilterFiles(string path, params string[] exts) {
return
Directory
.GetFiles(path)
.Where(file => !exts.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
}
You could try something like this:
var allFiles = Directory.GetFiles(#"C:\Path\", "");
var filesToExclude = Directory.GetFiles(#"C:\Path\", "*.txt");
var wantedFiles = allFiles.Except(filesToExclude);
I guess you can use lambda expression
var files = Array.FindAll(Directory.GetFiles(jobDir), x => !x.EndWith(".myext"))
You can try this,
var directoryInfo = new DirectoryInfo("C:\YourPath");
var filesInfo = directoryInfo.GetFiles().Where(x => x.Extension != ".pdb");
Afaik there is no way to specify the exclude patterns.
You have to do it manually, like:
string[] files = Directory.GetFiles(myDir);
foreach(string fileName in files)
{
DoSomething(fileName);
}
This is my version on the answers I read above
List<FileInfo> fileInfoList = ((DirectoryInfo)new DirectoryInfo(myPath)).GetFiles(fileNameOnly + "*").Where(x => !x.Name.EndsWith(".pdf")).ToList<FileInfo>();
I came across this looking for a method to do this where the exclusion could use the search pattern rules and not just EndWith type logic.
e.g. Search pattern wildcard specifier matches:
* (asterisk) Zero or more characters in that position.
? (question mark) Zero or one character in that position.
This could be used for the above as follows.
string dir = #"C:\Temp";
var items = Directory.GetFiles(dir, "*.*").Except(Directory.GetFiles(dir, "*.xml"));
Or to exclude items that would otherwise be included.
string dir = #"C:\Temp";
var items = Directory.GetFiles(dir, "*.txt").Except(Directory.GetFiles(dir, "*HOLD*.txt"));
i used that
Directory.GetFiles(PATH, "*.dll"))
and the PATH is:
public static string _PATH = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

Categories

Resources