Reputation: 1214
I am using the following to get the size of a file
FileInfo(filePath).Length
which of course works.
The file path is something like
Live\Sites\User\297387\XYZ - ABC
but an issue arises when the file is a duplicate
Live\Sites\User\297387\XYZ - ABC_2
Is there a way I can get the latest version of the file that name matches
Live\Sites\User\297387\XYZ - ABC
So I have the following files
Live\Sites\User\297387\XYZ - ABC
Live\Sites\User\297387\XYZ - ABC_1
Live\Sites\User\297387\XYZ - ABC_2
and I need to get the latest one that matches
Live\Sites\User\297387\XYZ - ABC
Upvotes: 0
Views: 418
Reputation: 460108
You can use the Path
class and LINQ:
string fileName = Path.GetFileName(filePath);
string dir = Path.GetDirectoryName(filePath);
var latestFile = new DirectoryInfo(dir)
.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly)
.Where(file => file.Name.StartsWith(fileName))
.OrderByDescending(file => file.LastAccessTime)
.First();
long len = latestFile.Length;
If you dont want to check the last access time but the number behind _
you can use this query:
var latestFile = new DirectoryInfo(dir)
.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly)
.Where(file => file.Name.StartsWith(fileName))
.Select(file =>
{
int index = file.Name.LastIndexOf('_');
string vStr = "0";
if(index >= 0)
vStr = file.Name.Substring(index + 1);
int version;
if(!int.TryParse(vStr, out version))
version = 0;
return new { file, version };
})
.OrderByDescending(xFile => xFile.version)
.Select(xFile => xFile.file)
.First();
Upvotes: 1
Reputation: 1987
This is my "cleanest" first-to-mind solution:
string regx = "file"; // replace this with your actual "base" file name
var f = Directory.EnumerateFiles("C:\\") // replace with your directory path
.Where(fn=>
System.Text.RegularExpressions.Regex.IsMatch(fn, regx, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
.Select(fn=>new FileInfo(fn))
.Aggregate( (f1,f2) => f1.LastWriteTime> f2.LastWriteTime? f1 : f2);
This will match all files in C:\ that has the word file in it - then select the most recently written file.
Upvotes: 1
Reputation: 154
This LinQ Query get the last file in Directory:
var lastFile = (from a in directoryInfo.EnumerateFiles()
orderby a.CreationTime descending
select a).FirstOrDefault();
or
var lastFile = (from a in directoryInfo.EnumerateFiles()
orderby a.CreationTime
select a).LastOrDefault();
Upvotes: 1
Reputation: 4443
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = " Live\Sites\User\297387\XYZ";
watcher.Changed += new FileSystemEventHandler(OnChanged);
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
Upvotes: 1