Filtered File Listing - c#

i have a project to make and i want in option 2 the user to give an extension/keyword for example and the program to search the directory for this and print all the files that include this extension/keyword and i need some help if it's possible.

Then use another overload of the Directory.GetFiles() method which accepts a search pattern as a parameter.
Check it out on MSDN. And here is an example.
var files = Directory.GetFiles(#"c:\", "*.exe");
Obviously, replace that second argument with a variable name where you store an input from a user.

Or perhaps something like:
IEnumerable<string> results = filePaths.Where(x => x.EndsWith(".exe"));

Related

Use Path.GetFileNameWithoutExtension method in C# to get the file name but the display is not complete

This is the simple C# code I wrote :
string file = #"D:\test(2021/02/10).docx";
var fileName = Path.GetFileNameWithoutExtension(file);
Console.WriteLine(fileName);
I thought I would get the string "test(2021/02/10)" , but I got this result "10)".
How can I solve such a problem?
I just wonder why would you want such behavior. On windows slashes are treated as separator between directory and subdirectory (or file).
So, basically you are not able to create such file name.
And since slashes are treated as described, it is very natural that method implementation just checks what's after last slash and extracts just filename.
If you are interested on how the method is implemented take a look at source code

How to get files names inside folder using regular expression in c#

I need to retrieve all files names inside a specific folder, but I need to use regular expression in which I need to get files names depends on a number in the file name. For example :
fitness-0Chromosom1
I mean zero in this case, I wrote the following:
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:/Users/Welcome/Desktop/Rounds/Fitness/AUV" + 1).GetFiles("fitness-"+geneticIteration+"*"+".txt");
Where geneticIteration is the number represent 0. Is it true or not?
Yes, your code above will return all file names matching "fitness-[a number]*.txt" in directory "C:/Users/Welcome/Desktop/Rounds/Fitness/AUV1".
Example results could be (given that "a number" = 0):
fitness-0Chromosom1.txt
fitness-0abc.txt
fitness-0.txt
GetFiles(path) also accepts the another parameter called 'searchPattern' where you can pass your regular expression. Another way to match the file name with your regular expression is using the Regex.IsMatch(path, pattern), which will return the true or false based on the comparison/match.

How to use GetFiles() search to include doc files but excude docx files?

Currently I am looping through my file system like this
For Each filename As String In Directory.GetFiles(sourceFolder, "*.doc")
However this is including docx files to the list of files that GetFiles returns. I wish to only search for doc files and not docx. Any idea if there is a truncate or stop search character I can use in the search pattern?
This is the default behaviour of GetFiles, you can use LINQ to do further filtering.
var files = Directory.GetFiles(#"C:\test", "*.doc")
.Where(file=> file.EndsWith(".doc", StringComparison.CurrentCultureIgnoreCase))
.ToArray();//If you want an array back
Directory.GetFiles Method (String, String)
When you use the asterisk wildcard character in a searchPattern such
as "*.txt", the number of characters in the specified extension
affects the search as follows:
If the specified extension is exactly three characters long, the method returns files with extensions that begin with the specified extension. For example, "*.xls" returns both "book.xls" and "book.xlsx".
Given the fact that you want to iterate over your files and considering the default behavior of these methods I suggest to use EnumerateFiles instead of GetFiles. In this way you could add a simple check on the extension of the current file
foreach(string filename in Directory.EnumerateFiles(sourceFolder, "*.doc"))
{
if(!filename.EndsWith("x", StringComparison.CurrentCultureIgnoreCase))
{
.....
}
}
Not elegant as the Linq only solution but still working and not creating an array of all the filenames present in the directory
I am not a C# programmer so may be there can be syntax mistake, but i think it may solve your problem.
foreach (FileInfo fi in di.GetFiles("*.doc")
.Where(fi => string.Compare(".doc", fi.Extension,
StringComparison.OrdinalIgnoreCase) == 0))
{
myFiles.Add(fi);
}

Find file by name and unknown extension C#

Are there any clever ways to easily find a file by its name and unknown extension in C#?
I have a image folder with images of different types .jpg, .gif and .png.
And all the program knows is the name of the image, and not the extension.
Is it possible to get the file by its name, without doing some big recursive resource consuming loop?
You could use the EnumerateFiles method and specify a search pattern:
var files = Directory.EnumerateFiles(#"c:\work", "somefilename.*");
This will of course return an IEnumerable<string> of all files that match this search pattern. If you know there can only be one, or wanted to get the first in the list, just chain it with LINQ to further filter the results.
Yes, it is possible. Use overloaded Directory.GetFiles method which accepts search pattern as second parameter:
string[] files = Directory.GetFiles(#"c:\images", fileName + ".*");
Linq to rescue
var filenames = Directory.GetFiles(#"C:\Windows\System32").Select(f => Path.GetFileName(f)).Where(fn => fn.StartsWith("ap"));
Let linq do the looping and filtering for you
There is a couple of options:
Build your file index in advance (simple dictionary will do the
trick).
Use windows search API.
Use EnumerateFiles, altough performance wise this is similar to a bit optimized big recursion traverse.

C# - Check filename ends with certain word

Hi I would like to know how to validate a filename in C# to check that it ends with a certain word (not just contains but is located at the end of the filename)
e.g I want to modify certain files that end with the suffix Supplier so I want to validate each file to test if it ends with Supplier, so LondonSupplier.txt, ManchesterSupplier.txt and BirminghamSupplier.txt would all be validated and return true but ManchesterSuppliers.txt wouldn't.
is this even possible? I know you can validate a filename to test for a certain word anywhere within a filename but is it possible to do what i'm suggesting?
Try:
Path.GetFileNameWithoutExtension(path).EndsWith("Supplier")
if (myFileName.EndsWith("whatever"))
{
// Do stuff
}
By utilizing the System.IO.Path.GetFileNameWithoutExtension(string) method, you can extract the filename (sans extension) from a string. For example, calling it with the string C:\svn\trunk\MySourceFile.cs would return the string MySourceFile. After this, you can use the String.EndsWith method to see if your filename matches your criteria.
Linq solution:
var result = FilePaths.Where(name => Path.GetFileNameWithoutExtension(name).EndsWith("Supplier"))
.Select(name => name).ToList();
Assuming that FilePaths is a list containing all the paths.

Categories

Resources