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");
Related
I'm using below code to look for files which carry any of these keywords. For now I could only look for kword1 and if no files found, I start repeating the search for kword2. I'm wondering if there is a more efficient way to look for kword1 or kword2 in the same search. I've been looking on multiple sources and I cant seem to find the way.
Here is what I`ve done so far:
string[] matches =
Directory
.GetFiles(
path1,
"*" + kword1 + "*.txt",SearchOption.AllDirectories
);
Here are a couple of tricks you can do using System.Linq. First set up the test run like this:
var directoryToSearch = AppDomain.CurrentDomain.BaseDirectory;
string
kword1 = "exe",
kword2 = "pdb";
The Where expression retrieves all the files, then filters them according to kword1 and kword2.
var files =
Directory
.GetFiles(
directoryToSearch,
"*",
SearchOption.AllDirectories)
.Where(filename=> filename.Contains(kword1) || filename.Contains(kword2));
The Select expression selects only the file name portion of the full path.
Console.WriteLine(
string.Join(
Environment.NewLine,
files.Select(file=>Path.GetFileName(file))));
I'm trying to fetch a particular filename from a directory. The code I've tried is as below
DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
FileInfo recentlyModLogFile = (from files in dirInfo.GetFiles("^Monarch_[0-9]{2}$") orderby files.LastWriteTime descending select files).First();
//Output : Error
List of file names (Input)
Monarch_05bridge //Date modified 16-12-2021 20:41
Monarch_04bridge //Date modified 16-12-2021 06:49
Monarch_04 //Date modified 16-12-2021 05:39
Monarch_02 //Date modified 16-12-2021 05:49
Monarch_02bridge //Date modified 14-12-2021 19:34
Monarch_01 //Date modified 14-12-2021 09:08
Code should look for files whose filename starts with Monarch_ followed by 2 numeric digits and then filter out the recently modified file
So the output should be Monarch_02
I also tried doing
DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
FileInfo recentlyModLogFile = (from files in dirInfo.GetFiles(Monarch_ + "*") orderby files.LastWriteTime descending select files).First();
//OUtput : Monarch_05bridge
Can someone help me to resolve this issue.
string youngestFile = Directory.GetFiles(directoryPath)
.Where(o => Regexp.Contains(Path.GetFileNameWithoutExtension(o), "Monarch_\\d\\d"))
.OrderByDescending(o => File.GetLastWriteTime(o))
.FirstOrDefault();
This is a quick copy-and-paste from my project files. The Regexp.Contains() is one of the simple methods I wrote to do regexp comparisons.
Notice the Regular Expression I used allow Monarch_02, Monarch_02Bridge and abcMonarch_09 all to be possible result. You can use "^Monarch_\\d\\d$", if you want a strict rule.
Refer to Regular Expressions for details.
private static Match GetFirstMatch(string text, string pattern)
{
Match match = Regex.Match(text, pattern, RegexOptions.None);
return match;
}
public static Boolean Contains(string text, string pattern)
{
return GetFirstMatch(text, pattern).Value != String.Empty;
}
Basically, use Directory.GetFiles(path) to get all the files, then use LINQ to apply conditions, order-bys and fetch the first result.
The Path, Directory and File classes can help a lot when you are working around file system.
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")
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);
I have a folder with files named
myfileone
myfiletwo
myfilethree
How can I check if file "myfilethree" is present.
I mean is there another method other than IsFileExist() method, i.e like filename contains substring "three"?
Substring:
bool contains = Directory.EnumerateFiles(path).Any(f => f.Contains("three"));
Case-insensitive substring:
bool contains = Directory.EnumerateFiles(path).Any(f => f.IndexOf("three", StringComparison.OrdinalIgnoreCase) > 0);
Case-insensitive comparison:
bool contains = Directory.EnumerateFiles(path).Any(f => String.Equals(f, "myfilethree", StringComparison.OrdinalIgnoreCase));
Get file names matching a wildcard criteria:
IEnumerable<string> files = Directory.EnumerateFiles(path, "three*.*"); // lazy file system lookup
string[] files = Directory.GetFiles(path, "three*.*"); // not lazy
If I understand your question correctly, you could do something like
Directory.GetFiles(directoryPath, "*three*")
or
Directory.GetFiles(directoryPath).Where(f => f.Contains("three"))
Both of these will give you all the names of all files with three in it.
I am not that familiar with IO but maybe this would work ? Requires using System.Linq
System.IO.Directory.GetFiles("PATH").Where(s => s.Contains("three"));
EDIT: Note that this returns array of strings.