Deleting multiple files with wildcard - c#

You know that in linux it's easy but I can't just understand how to do it in C# on Windows. I want to delete all files matching the wildcard f*.txt. How do I go about going that?

You can use the DirectoryInfo.EnumerateFiles function:
var dir = new DirectoryInfo(directoryPath);
foreach (var file in dir.EnumerateFiles("f*.txt")) {
file.Delete();
}
(Of course, you'll probably want to add error handling.)

I know this has already been answered and with a good answer, but there is an alternative in .NET 4.0 and higher. Use Directory.EnumerateFiles(), thus:
foreach (string f in Directory.EnumerateFiles(myDirectory,"f*.txt"))
{
File.Delete(f);
}
The disadvantage of DirectoryInfo.GetFiles() is that it returns a list of files - which 99.9% of the time is great. The disadvantage is if the folder contains tens of thousands of files (which is rare) then it becomes very slow and enumerating through the matching files is much faster.

You can use the Directory.GetFiles method with the wildcard overload. This will return all the filenames that match your pattern. You can then delete these files.

I appreciate this thread is a little old now, but if you want to use linq then
Directory.GetFiles("f:\\TestData", "*.zip", SearchOption.TopDirectoryOnly).ToList().ForEach(File.Delete);

Related

Find files whose path ends with certain pattern

Given a file is in C drive, and its path ends with "Framework64\v4.0.30319\WPF\Fonts\GlobalMonospace.CompositeFont", what is the most efficient way to find the file?
It may be able to find, for example, "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\Fonts\GlobalMonospace.CompositeFont".
I can implement it in C# or AutoHotKey. I think Directory.EnumerateFiles and loop directive will work, but what is the most efficient way?
Use Directory.EnumerateDirectories with option SearchOption.AllDirectories to find all directories. Then pick those whose path ends in "Framework64\v4.0.30319\WPF\Fonts". Then for those, check whether the file "GlobalMonospace.CompositeFont" exists in those directories using File.Exists.
Loop, C:\*Framework64\v4.0.30319\WPF\Fonts\GlobalMonospace.CompositeFont, , 1 ; recurse into subfolders
{
MsgBox, 4, , Filename = %A_LoopFileFullPath%
continue?
IfMsgBox, No
break
}
https://autohotkey.com/docs/commands/LoopFile.htm

Directory.GetFiles - Search pattern for file extensions [duplicate]

This question already has answers here:
Directory.GetFiles of certain extension
(3 answers)
Closed 8 years ago.
I need to get all ASP files in a folder, so I wrote a code like this:
string[] files = Directory.GetFiles(#"C:\Folder", "*.asp", SearchOption.AllDirectories);
However, it also returns files with extension "aspx".
Is there a way to specify the end of the extension?
Sorry for my english and thanks in advance.
Is there a way to specify the end of the extension?
There isn't a way to do this directly. The best option would be to switch to Directory.EnumerateFiles and filter afterwards:
var files = Directory.EnumerateFiles(#"C:\Folder", "*.asp", SearchOption.AllDirectories)
.Where(f => f.EndsWith(".asp", StringComparison.OrdinalIgnoreCase));
This is because the Directory methods have specific behavior which prevents this from working directly. From the docs:
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".
This is an exception to the normal search rules, but, in your case, is working against you. Using EnumerateFiles streams the results, and filtering afterwards allows you to find only the proper matches.
Unfortunately, i don't think there's a built in way. but
Directory.EnumerateFiles(#"C:\Folder", "*.asp", SearchOption.AllDirectories).Where(f => f.EndsWith(".asp")
should be as performant as a direct query would be. (note that EnumerateFiles returns an IEnumerable and is preferable to GetFiles if you don't need the files actually in an array)

How to count the number of matches of files in a directory

I was looking many questions after answering this.
How I find if in a directory exists at least one (and better if you give me the number of) files which matches a certain regular expression?
I know I can loop the files in the directory with this answer
But there is a way of counting without looping?
I try with count() but that don't work
Taken from your linked question / answer, this should work:
int count = Directory.GetFiles(#"c:\temp").Count(path => Regex.IsMatch(path, pattern));
If the pattern is simple, then GetFiles in Directory already provides the information without using RegEx.
int count = Directory.GetFiles(#"c:\", "*.txt", SearchOption.AllDirectories).Count();
You can get them without the bottom foreach loop by using the Length property of the array returned by the Directory.GetFiles method.
int count = matches.Length;
http://msdn.microsoft.com/en-us/library/system.array.length.aspx

converting filenames to lower case

was hoping for some advice as to how to convert existing file names in a folder...all to lower case.
I felt that a good start would be to save the file names in a list and convert them all to lower.
How can I replace the existing file names in the folder to the lower case ones?
List<string> codes = new List<string>();
string[]productCodes = Directory.GetFiles(#"C:\Users\Ariang\Desktop\screenshotslowercase\screenshots");
codes = productCodes.ToList();
codes = codes.ConvertAll(t => t.ToLower());
This should work:
foreach (var file in Directory.GetFiles(#"C:\Temp\testrename"))
{
File.Move(file, file.ToLowerInvariant());
}
A few notes, first of all I have tested this and it works, somebody else mentioned using a temporary variable, but I haven't needed to do this.
Also, I have run this multiple times on the same directory, and I don't get an IOException the second or third time around, so I don't think any additional checking is necessary.
However, I am on Windows 8 and targeting .Net 4.5, things may be different on earlier versions of Windows or .Net.
Windows system doesn't see difference betweeen lower and upper letters in file names. Thats why you can't convert like "MyFile" -> "myfile". Use two steps instead:
foreach (var file in Directory.GetFiles(#"C:\Temp\testrename"))
{
var tempName = "." + file.ToLowerInvariant();
File.Move(file, tempName);
File.Move(tempName, file.ToLowerInvariant());
}
no need for list and all that. Simple read the file name from directory and use
System.IO.File.Move("oldfilename", "oldfilename".ToLower());
string[] files = Directory.GetFiles(dir);
foreach(string file in files)
{
System.IO.File.Move(file, file.ToLowerInvariant());
}

Searching for strings in DirectoryInfo

I am having some trouble searching directories for Files that have certain criteria in their file names. Below is my code and it captures the correct Files most of the time but sometimes skips the files it needs to capture. What is the best way to do this?
Many thanks.
So below I'm trying to capture All Files in a Directory that have the word "FINAL" and the correct Actual_Date. I have a datatable called dtResult2 that has these Actual_Dates stored in them.
foreach (DataRow drow in dtResult2.Rows)
{
//check for Null and start searching if not Null
if(drow["Well_Name"] != DBNull.Value)
{
//Now lets start searching the entire ARCHIVE folder/subfolders for a DWG that has
//this Well_Name and Actual_Date with FINAL in File Name...
DirectoryInfo myDir = new DirectoryInfo(myCollection3[v]);
//Collect the Final, Approved DWGs only...
var files = myDir.GetFileSystemInfos().Where(f => f.Name.Contains("FINAL") || f.Name.Contains(drow["Well_Name"].ToString()) || f.Name.Contains(drow["Actual_Date"].ToString()));
//More code not shown due to premise of question..
}
}
there is nothing wrong with the code probably the where condition is wrong.
I can suggest you to convert it into a classic for/foreach which allows you to debug the conditions and is also more performant. You can even convert it back to a LINQ expression as soon as you have identify the bug
Most likely the problem lies with the use of the Contains method which is case sensitive:
f.Name.Contains("FINAL") will not match "Final" it will only match "FINAL".
Use IndexOf for better results for case insensitive comparisons.

Categories