Show list from last file to first save - c#

I want to reverse the result displayed in a Combobox.
The last saved file would appear first, currently it is the opposite. it appears with this code:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
foreach (string file in files)
{
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}
According to my research, the solution would be:
.OrderByDescending(p => p.CreationTime).ToArray();
added somewhere. But I don't know. Every attempt I've made has been unsuccessful.
Currently:
101-00.06.52.TXT
101-00.06.54.TXT
101-00.06.56.TXT
Desired outcome:
101-00.06.56.TXT
101-00.06.54.TXT
101-00.06.52.TXT
Does anyone know?

Instead of static method Directory.GetFiles() method, use GetFiles() method from DirectoryInfo class. Apply OrderByDescending() on it.
Directory.GetFiles():
Returns the names of files that meet specified
criteria
Vs
DirectoryInfo.GetFiles():
Returns a file list from the current directory.
Like,
DirectoryInfo di = new DirectoryInfo(#"C:\Test\"); //Get the Directory information
var allTxtFiles = di.GetFiles("*.txt") //Get all files based on search pattern
.OrderByDescending(p => p.CreationTime) //Sort by CreationTime
.Select(x => x.Name); //Select only name from FileInfo object
foreach (string file in allTxtFiles)
{
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}

I don't know the reason why you problem. But if you want to receive correct result is simple. First try this:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
comboBox1.ItemsSource = files;
if the result is not correct. Use this:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
files = files.Reverse();
comboBox1.ItemsSource = files;

Related

how to apply descending order according to creation time of the files [duplicate]

I am using Directory.GetFiles to get files from a particular folder.
By default files from that folder are coming sort by filename ie. in alphabetical order of filename. I want to get files in the order in which files are modified.
I cannot use Directory.GetInfo as I want to get the files which contain particular keyword.
Please let me know how can we get the file sorted by their modified date.
I am using the following code
string[] arr1 = Directory.GetFiles("D:/TestFolder", "*"Test12"*");
Any help would be greatly appreciated.
what about the below
DirectoryInfo di = new DirectoryInfo("D:\\TestFolder");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.Where(f=>f.Name.StartsWith("Test12"))
.OrderBy(f => f.CreationTime)
.ToList();
you can replace f.Name.StartWith with any string function against your need (.Contains,etc)
you can replace f => f.CreationTime with f.LastWriteTime to get the modified time but bear in mind that starting in Windows Vista, last access time is not updated by default. This is to improve file system performance
if you change to directory info you could do
FileInfo[] files = new DirectoryInfo("path")
.GetFiles("filter")
.OrderBy(f => f.CreationTime)
.ToArray();
Edit:
Saw you wanted modified date, can do that with f.LastWriteTime instead
Try this way. It will work...
string path = "C:\\Users", FileName="YourFileName";
DirectoryInfo direct= new DirectoryInfo(path);
FileInfo[] files = direct.GetFiles();
Array.Sort(files , (x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.CreationTime, y.CreationTime));
files = Array.FindAll(files , a => a.FullName.Contains(FileName) == true);
foreach(var file in files){
// do what you want..
Console.WriteLine(file.FullName);
}

How to get files from a specific sub-directories using c#?

I'm trying to get all *.html files which are inside sub-directories named abcd to an array.
The path given can contain multiple *.html files in multiple sub-directories and even in the root directory(i.e. immediately inside the user given path) but I only want those *.html files which are inside the specificly named sub-directories(abcd) using LINQ.
This is what I tried
string workingPath = #"D:\Testing";
string[] myFiles = workingPath.Select(dirs => Directory.GetDirectories(workingPath)
.Select(folders => (from item in Directory.GetDirectories(folders, "abcd", SearchOption.AllDirectories)
.Select(item => Directory.GetFiles(item, "*.html"))
)));
I'm getting an error
A query body must end with a select clause or a group clause (CS0742)
. How do I fix this?
Your code does not look like it will compile. To start with workingPath.Select will return a collection of chars and you are trying to iterate over that again , which does not make sense considering your requirements.
You need something like this
var files = new List<string>();
if (Directory.Exists(workingPath))
{
foreach (var f in Directory.GetDirectories(workingPath, "abcd",
SearchOption.AllDirectories))
{
files.AddRange(Directory.GetFiles(f, "*.html"));
}
}
You can also do a one liner using LINQ
var files2 = Directory.GetDirectories(workingPath, "abcd", SearchOption.AllDirectories)
.SelectMany(d => Directory.GetFiles(d, "*.html")).ToArray();

How to get the latest file with multiple filters C#

I have this simple code which I need to update a little bit.
I need to update the list(this.FoundReports) with only the very latest file if multiple instances of the same file type are located in directories. .i.e _InputCounts or_OutputCounts.
How to do it with the existing code or maybe there is a better way?
Thanks
Here what you can do:
You can create a string[] array to store all the files information in that specific directory and them compare the dates of each file:
Try something like this:
path = locations of file
findname = file name you are looking for
string[] dirs = Directory.GetFiles(path, findName);
foreach (string dir in dirs)
{
DateTime lastupdatedate = File.GetLastWriteTime(dir);
//here you compare last updated date and find your record.
if (lastupdatedate > previousLastupdated)
{
}
}

is there a way to delete the oldest file in a directory? using c#

So i have a directory on my local laptop. Where my program stores xml documents. But i want the program to be able to find the oldest and delete that if there are more that 100 documents in the directory. this is the way i check the amount of xml documents in the directory.
private int CheckAmountOfFiles()
{
var fileCount = (from file in Directory.EnumerateFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "*.xml", SearchOption.TopDirectoryOnly) select file).Count();
return fileCount;
}
I dont know if this i possible? hope one of you can give me a hand.
First order the retreived list by the creation date, skip the first 100 elements and take all remaining into a list. Then delete all files from that list.
var oldFiles = Directory.EnumerateFiles(/*...*/)
.Select(i => new FileInfo(i))
.OrderByDescending(i => i.DateCreated)
.Skip(100);
foreach(var file in oldFiles)
{
file.Delete();
}
Something like this:
var last = Directory.EnumerateFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
.Select(fileName => new FileInfo(fileName))
.OrderByDescending(fileInfo => fileInfo.LastWriteTime) // or "CreationTime"
.Skip(100) // Skip 100 newest files
.Select(fileInfo => fileInfo.FullName);
...
foreach (var fileName in last)
File.Delete(fileName);
Note, that in order to get required time you have to use FileInfo class

c# Directory.GetFiles file structure from app root

I have the following piece of code:
string root = Path.GetDirectoryName(Application.ExecutablePath);
List<string> FullFileList = Directory.GetFiles(root, "*.*",
SearchOption.AllDirectories).Where(name =>
{
return !(name.EndsWith("dmp") || name.EndsWith("jpg"));
}).ToList();
Now this works very well, however the file names with it are quire long.
is there a way i can take out the path till root? but still show all the subfolders?
Root = C:\Users\\Desktop\Test\
But the code would return the whole path from C:
while I'd prefer if I could take out the root bit straight away. but still keep the file structure after it.
eg
C:\Users\\Desktop\Test\hi\hello\files.txt
would return
\hi\hello\files.txt
I know i can just iterate over the file list generated and remove it all one by one, I'm wondering if I can just filter it out stright.
Using the power of LINQ:
string root = Path.GetDirectoryName(Application.ExecutablePath);
List<string> FullFileList = Directory.GetFiles(root, "*.*", SearchOption.AllDirectories)
.Where(name =>
{
return !(name.EndsWith("dmp") || name.EndsWith("jpg"));
})
.Select(file => file.Replace(root, "")
.ToList();

Categories

Resources