Find files by not like mask - c#

I need to load files from a directory with search option. I created two search patterns, first I must find files begining with "Client" and without the "_delete" extension.
The second search must find files begining with "Client" and with extension "_delete".
I implemented test code, but did not find files.
string mask_not_like = #"Client*[^_delete\s].xlsx";
string mask = "Client*_delete.xlsx";
path1 = "c:\Client_Test.xlsx";
path2 = "c:\Client_Test_delete.xlsx";
var searchPattern1 = new Regex(mask_not_like, RegexOptions.IgnoreCase);
var searchPattern2 = new Regex(mask, RegexOptions.IgnoreCase);
var files1 = Directory.GetFiles(path1).Where(f => searchPattern1.IsMatch(f));
var files2 = Directory.GetFiles(path1).Where(f => searchPattern2.IsMatch(f));

Well, the first problem is that you're passing file paths to a method which expects a directory.
path1 = "c:\Client_Test.xlsx";
// path one is not a directory...
var files1 = Directory.GetFiles(path1).Where(f => searchPattern1.IsMatch(f));
That should throw an IOException since path1 is a file name.
Next, you're overcomplicating things. No regex is required (or warranted).
You have two cases; files which begin with "Client" and end in "_delete", and those which begin with "Client" and do not. "Client" is common to both, so, just grab all files which begin with client, next find those that end in "_delete", and the rest are those which do not end in "_delete".
var allFiles = Directory.GetFiles(path, "Client*.xlsx");
var endInDdelete = allFiles.Where(f => Path.GetExtension(f) == "._delete");
var doNotEndInDelete = allFiles.Except(endInDelete);
EDIT: I just noticed that you erroneously say that the extension is "_delete", when in reality, it's just the end of the file name. So...
var allFiles = Directory.GetFiles(path, "Client*.*");
var endInDdelete = allFiles.Where(f => Path.GetFileNameWithoutExtension(f).EndsWith("_delete");
var doNotEndInDelete = allFiles.Except(endInDelete);

Why even bother with regex?
var clientFiles = Directory.GetFiles("C:\\", "Client*.xlsx");
var clientFilesWithDelete = clientFiles.Where(clientFile => clientFile.EndsWith("_delete.xlsx"));
var clientFilesWithoutDelete = clientFiles.Except(clientFilesWithDelete);

Related

Find the most recent file saved under same name but in different directories using .NET C#

The directories are the 3 below
filename = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
filenameprint = System.Environment.CurrentDirectory;
pathload = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
And the file is saved as printout.pdf in all the 3 directories.
I'm thinking of using the LastWriteTime function but I do not know how to stack for the latest.
This should do the trick:
var files = new List<string>() {filename, filenameprint, pathload};
var newestFile = files.Select(file => new FileInfo(file)).OrderByDescending(f => f.LastWriteTime).First();
Edit: naturally you will have to combine the filename with the paths, otherwise this does not make much sense.

How to Remove Directories From EnumerateFiles?

So I'm working on a program that will list all the files in a directory. Pretty simple. Basically, when I do this: List<string> dirs = new List<string>(Directory.EnumerateFiles(target));, I don't want it to include the directory and all. Just the file name. When I run my code;
List<string> dirs = new List<string>(Directory.EnumerateFiles(target));
Console.WriteLine($"Folders and files in this directory:\n");
foreach (string i in dirs) {
Console.WriteLine($"> {i}");
}
it gives me the following:
C:\Users\Camden\Desktop\Programming\Visual Studio\C#\DirectoryManager\DirectoryManager\bin\Debug\DirectoryManager.exe
I just want the DirectoryManager.exe part, so I looked it up and I found that you can replace strings inside of strings. Like so: i.Replace(target, "");. However, this isn't doing anything, and it's just running like normal. Why isn't it replacing, and how should I instead do this?
Use methods from the System.IO.Path class.
var fullfile = #"C:\Users\Camden\Desktop\Programming\Visual Studio\C#\DirectoryManager\DirectoryManager\bin\Debug\DirectoryManager.exe";
var fileName = Path.GetFileName(fullfile); // DirectoryManager.exe
var name = Path.GetFileNameWithoutExtension(fullfile); // DirectoryManager
The simplest way is to use the Select IEnumerable extension
(you need to have a using Linq; at the top of your source code file)
List<string> files = new List<string>(Directory.EnumerateFiles(target)
.Select(x => Path.GetFileName(x)));
In this way the sequence of files retrieved by Directory.EnumerateFiles is passed, one by one, to the Select method where each fullfile name (x) is passed to Path.GetFileName to produce a new sequence of just filenames.
This sequence is then returned as a parameter to the List constructor.
And about your question on the Replace method. Remember that the Replace method doesn't change the string that you use to call the method, but returns a new string with the replacement executed. In NET strings are immutable.
So if you want to look at the replacement you need
string justFileName = i.Replace(target, "");
An alternative to using Directory.EnumerateFiles, would be DirectoryInfo.EnumerateFiles. This method returns an IEnumerable<FileInfo>. You can then make use of the FileInfo.Name property of each of the returned objects. Your code would then become:
var files = new DirectoryInfo(target).EnumerateFiles();
Console.WriteLine("Files in this directory:\n");
foreach (FileInfo i in files) {
Console.WriteLine($"> {i.Name}");
}
For just the list of file names:
List<string> fileNames = new DirectoryInfo(target).EnumerateFiles().Select(f => f.Name).ToList();
Alternatively, if you want both files and directories, you can use EnumerateFileSystemInfos. If you need to know if you have a file vs a directory you can query the Attributes property and compare it to the FileAttributes flags enumeration.
var dirsAndFiles = new DirectoryInfo(target).EnumerateFileSystemInfos();
Console.WriteLine("Folders and files in this directory:\n");
foreach (var i in dirsAndFiles) {
var type = (i.Attributes & FileAttributes.Directory) == FileAttributes.Directory ? "Directory" : "File";
Console.WriteLine($"{type} > {i.Name}");
}
The FileSystemInfo.Name property will return either the file's name (in case of a file) or the last directory in the hierarchy (for a directory)--so just the subdirectory name and not the full path ("sub" instead of "c:\sub").

Searching with System.IO.Directory.GetFiles and wildcards in path

I have a curious problem in a C#-program.
I have some local folderpaths like
"C:\test\AB_Systems\ELEGANCE\CB-DOC\live\M7-091.249.99.XX.01\extobjects".
Now i want to search for PDF-files in the subfolder called "extobjects".
Unfortunately there are many subfolders in the folder "live", which got a subfolder called "extobjects", so i thought it would be better to use a wildcard in the searchpath like that:
"C:\test\AB_Systems\ELEGANCE\CB-DOC\live\*\extobjects"
But this doesn't work.
Is there a way do do this?
public static FileInfo[] findFile(String whereToSearch, String searchFor , String mode)
{
IEnumerable<FileInfo> files = null;
if (mode.Equals(""))
mode = "s";
if (searchFor.Equals(""))
searchFor = "*";
if (mode.Equals("r") || mode.Equals("recursive"))
{
DirectoryInfo dir = new DirectoryInfo(whereToSearch);
files = dir.EnumerateFiles(searchFor, searchOption: SearchOption.AllDirectories);
}
if (mode.Equals("s") || mode.Equals("specific"))
{
DirectoryInfo dir = new DirectoryInfo(whereToSearch);
files = dir.EnumerateFiles(searchFor, searchOption: SearchOption.TopDirectoryOnly);
}
if (files != null) return files.ToArray<FileInfo>();
else return null;
}
That's an example how to do it.
It's important to say that only the filename can contain a wildcard pattern like *. The Path can be given as where to start the search and by giving searchOption: searchOption.AllDirectories as an argument it will go through all sub-directories of the entry path.
You will receive an Array of FileInfo which objects that contain the the path and more information.
You can use Linq like this:
var files = Directory
.EnumerateDirectories(#"C:\test\AB_Systems\ELEGANCE\CB-DOC\live", "extobjects", SearchOption.AllDirectories)
.SelectMany(x => Directory.EnumerateFiles(x, "*pdf", SearchOption.TopDirectoryOnly))
.ToArray();
I'd choose a solution exactly what BugFinder proposed, you could optimize the following foreach-loop into a LINQ query if your .NET target supports it.
// Itterate subdirectories of the live folder
foreach (var subDir in Directory.GetDirectories(#"C:\test\AB_Systems\ELEGANCE\CB-DOC\live"))
{
// Check if path to extobjects exists
var extObjects = Path.Combine(subDir, "extobjects");
if (Directory.Exists(extObjects))
{
var pdfFiles = Directory.GetFiles(extObjects, "*").Where(x=>x.EndsWith(".pdf"));
// Do something with the pdf file paths
}
}

How to get folder in directory by part of the name

I am trying to figure out how to get the name of a folder in certain directory, but the folder name I need is generated randomly, but its name always ends in .user (for example the folder could be 1245fa.user or WRf5.user).
How can I do that?
Here is how I am getting a folder with a name that never changes
string slug = #"%userprofile%\AppData\Roaming\MyApp\Profiles\constantuser\";
string filePath = Environment.ExpandEnvironmentVariables(slug);
string targetPath = #"C:\ErrorLog";
string sourceFile = System.IO.Path.Combine(filePath, p);
string destFile = System.IO.Path.Combine(targetPath, p);
In this case I would need the constantuser to be the folder that ends with .user
You can try Where() (or First(), Single(), ...) LINQ extensions on Directory.EnumerateDirectories().
Assuming the following code (note the slug ending in the "parent" directory):
var slug = #"%userprofile%\AppData\Roaming\MyApp\Profiles\";
var parentDirectoy = Environment.ExpandEnvironmentVariables(slug);
If you know for sure there's exactly one directory matching the criterion, you can do this:
var directoryName = Directory.EnumerateDirectories(parentDirectory)
.SingleOrDefault(dir => dir.EndsWith(".user"));
if (directoryName != null)
{
// do your thing
}
If you use Single instead of SingleOrDefault, a missing directory or more than one directory will result in an Exception instead of returning null.
If there may be multiple directories, you can do this instead:
var directoryNames = Directory.EnumerateDirectories(parentDirectory)
.Where(dir => dir.EndsWith(".user"));
foreach (var directoryName in directoryNames)
{
// do your thing
}
Where the loop may either run zero times if no matches are found or multiple times; one for each match.
System.IO.Directory.GetDirectories(filePath, "*.user")

LINQ expression until to break a string

Using LINQ I'm looking to break down the following path string[], however I'd like to break it up to the point of the Binn folder. Is there a WHERE UNTIL operator in LINQ?
c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Binn\sqlservr.exe
What I'd like todo
var words = from word in thepath
where UNTIL thepath == "Binn"
select word;
First, split the path:
var parts = path.Split('\\');
To get the part up to (but not including) "Binn":
var start = parts.TakeWhile(p => p != "Binn");
To get the part after (and including) "Binn":
var rest = parts.SkipWhile(p => p != "Binn");
You can also use Skip or Take to consume or discard a specific number of items from the sequence.
Though if you just want the filename part of a path, use Path.GetFileName.
Use the Enumerable.TakeWhile extension method. AFAIK, there is no LINQ syntax for this.
var words = thepath.TakeWhile(word => word != "Binn");
off the top of my head
var path = #"c:\ Program Files\ Microsoft SQL Server\ MSSQL10.SQLEXPRESS\ MSSQL\ Binn\ sqlservr.exe";
var words = path.Split('\\');
var filteredWords = words.TakeWhile(w => w != "Binn");
You could have used a regex
using System.Text.RegularExpressions;
...
String path = #"c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Binn\sqlservr.exe";
path = Regex.Replace(path, #".*\\Binn", "Binn");

Categories