Add FileName in ListView - c#

Consider that in Folder xxx I have 3 files and I want to return the names of those 3 file in a ListView.
My updater function runs every second, which means that the ListView items must always be updated with the new files.
How do I do this?

You can use the DirectoryInfo class.
https://msdn.microsoft.com/en-us/library/4cyf24ss(v=vs.110).aspx
You should call the GetFiles() method, which will return a list with the file names presented in the directory.

Related

How to get list of .xlsx file in C#

I am developing Windows Form application and I want to have a list of .xlsx files in the folder say -
C:\Equipment\Exchanger\AES\
The folder may contain files like -
00-E-001,
00-E-002,
03-E-005,
04-E-001 and so on..
I don't want to open file dialogs but want to see a combo box showing the FileName (no extension). Based on selection of combobox I want to show the values of certain cells in the various text boxes but that is later part.
You can use Directory.GetFiles to query the full path strings of every *.xlsx file in the folder, then strip it down to just the filename using Select and Path.GetFileName.. It makes sense (to me) to sort them alphabetically, then you just need them in a list so the combo can use them
yourCombo.DataSource = Directory.GetFiles(yourFolderPath, "*.xlsx").Select(Path.GetFileName).OrderBy(n => n.ToLower()).ToList();
If you don't want the extension in the combo (it's a waste of pixels :) ) you can use Path.GetFileNameWithoutExtension
When the time comes to get which file was selected by the user it's:
var fullPath = Path.Combine(yourFolderPath, yourCombo.SelectedItem);
(You'll have to add the extension back on if you used GetFilenameWithoutExtension: yourCombo.SelectedItem + ".xlsx")
I recommend you set your combo's DropDownStyle to DropDownList
First of all, your code should have a look at the folder, which contains needed files.
List<string> xlsxFiles = Directory.GetFiles(yourdirectory, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".xlsx" }
.Contains(Path.GetExtension(file)))
.ToList(); // Looking into directory and filtering files
for(int i = 0; i < xlsxFiles.Count; i++)
{
xlsxFiles[i] = Path.GetFileName(Path.ChangeExtension(xlsxFiles[i], null)); // Removes files' extensions
}
This is the simple way of looking into the directory and filtering files to needed ones.
Then, I suggest having a look into EPPlus library, which allows you to work directly with tables and cells, without manual extraction of the file
Here is the handy tutorial of using EPPlus

ListBox sorting by files creation time

My listBox1 is filled with names of txt files. It is sorting them automatically alphabetically. But I need to sort these files by creation time, from the newest to the oldest. Can someone help me?
you are not giving us much to go on :P
But I am going to give it my best shot to help you. Because I do not know how you have populated the List (by hand, or with code) I cant really guide you there.
But lets say you did it by code. The following snippet I typed might help you find what you need
//array of file names (these need to be paths to files, so if you do not prefix it with ./path/ or anything, then the executable needs to be in the same folder)
//If you are debugging, make sure the paths are correct if you expect them to be in the same folder, it should then be in the debug folder.
//If you included some test files in the solution and want them copied to your debug folder. Click on them, go to the properties pane, and set build action to content, and one of the other properties should read copy of newer instead of never copy
var fileNames = new string[]{"1.txt", "2.txt", "3.txt"};
var fileInfos = fileNames.Select(f => new FileInfo(f));
var orderedFileInfos = fileInfos.OrderBy(f => f.CreationTime);
orderedFileInfos is now a list of type FileInfo ordered by ascending on their creationtime.
This is what you can use to populate your ListBox
I hope i helped you progress in your project.

GetFoldersAsync sorted not by name but by last modified?

I want to display a list of recently modified items, sorted by date. They are contained in folders as there are multiple types of information I need to store for each item. All items are stored in the localfolder.
One way would be to rename the folders by their date when the item is modified, but this could create collisions if two items are modified at the same time. Is there a way to sort the folders by the last modified time that Explorer shows?
The DirectoryInfo objects GetDirectories() method returns an array of DirectoryInfo objects with the various dates populated -- including LastWriteTime.
Just sort by the appropriate property and do what you want with the result.
For reference: https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.getdirectories?view=netframework-4.7.1
If you are wanting the last modified date for the individual files within a folder, GetFiles()' method returns the an array ofFileInfo` objects, again with various date properties populated.
For reference: https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.getfiles?view=netframework-4.7.1
As an alternative, if the number of files/folders is large or has to be read frequently, it may be better to keep a text files in each folder and update it with each change to contain a summary of the current state of the files in that folder.

C# search for specific file and order by date

I've researched this across various threads and found viable solutions for one or two parts but I'm having trouble linking the two up. Basically I want to search a directory for file of a certain name , if there is is more than one occurance of this file I then want to choose only the most recent file. e.g if I have three files called DOG I only want the most recent one. I'm using version 1.0 so I don't think Linq is and option. here is the closest match to a solution I've found which I believe will pull the most recent file
var targetDirectory = new DirectoryInfo("G:\SomeFilePath");
string[] files = System.IO.Directory.GetFiles(Dts.Variables["User::DirectoryPath"].Value.ToString());
string lastFileName=string.Empty;
foreach (string Current_filename in files)
{
if (string.Compare(Current_filename,lastFileName)>=1)
{
lastFileName = Current_filename;
}
}
Dts.Variables["User::LastFileName"].Value = lastFileName;
As the files are all in the same directory my Query is if this code pulls the most recent file , how can I specify what most recent file I want , for example , I have 3 files called dog , 2 called cat etc so how can I take just the most recent Dog file and just the most recent Cat file.
based on answers in this thread I am using this solution https://stackoverflow.com/a/1781668/451518 to return the most recent files , however I know want to seperate these files based on names , e.g I want to search the directory for all DOG , or CAT txt files and then perform the order by most recent function as shown in the link
JUST TO CLARIFY the file names aren't exactly the same i mean DOG2 or DOG3 however its the DOG part that is important so based on the DOG I need to pick the most recent one
In my main I am calling
if(filename.StartsWith("DOG"))
{
GetLatestWritenFileFileInDirectory(directoryInfo);
}
However I want to edit the GetLatestWritenFileFileInDirectory so that it only takes the files with the name DOG

How to get all files from a folder in sorted order in C#.Net? [duplicate]

Is is possible to get files that is ordered same as in Windows Explorer
I know "natural sort", but it's not what I need, I need to get the file list ordered by the same attribute in Windows Explorer, for example:
If I ordered a directory by the attribute "create date", then I will get a file list as below:
name create date file size
1.txt 2012/1/1 125Kb
2.tab 2012/3/2 15Kb
3.bmp 2013/5/5 26Kb
If my windows explorer order file list with the attribute "file size", the the file list would be:
name create date file size
2.tab 2012/3/2 15Kb
3.bmp 2013/5/5 26Kb
1.txt 2012/1/1 125Kb
Could anyone help?
I think this is going to be a lot more complex than you expect. Folder settings are stored in the registry in two places:
HKCU\Software\Microsoft\Windows\Shell\BagMRU
HKCU\Software\Microsoft\Windows\Shell\Bags
The first path contains a structure which reflects the structure of the file system, and the second path contains details about those items, including a REG_BINARY value called "Sort" which records the sort order used for that folder.
See Willi Balenthin's website for details on the structure, including sample code (in Python)
Here's how to get a list of files sorted by their name:
var path = #"C:\windows"; // obviously change this to whatever you want
var files = System.IO.Directory.GetFiles (path).ToList ();
file.Sort();
And that's it!
Here's how you would do it per your given code sample:
var temperaturePressureSignalFilesList = Directory.GetFiles(TemperaturePressureSignalDirectory, "*.txt", SearchOption.TopDirectoryOnly).ToList();
temperaturePressureSignalFilesList.Sort();
using System.Linq;
DirectoryInfo info = new DirectoryInfo(""); FileInfo[] files =
info.GetFiles().OrderBy(p => p.CreationTime).ToArray(); foreach
(FileInfo file in files) {
// DO Something... }
here is the sample code for get files in directory by creation time.
You can get files by size same way.
I guess you are talking about viewing pane in Windows Explorer (it's essentially a Windows File Manager but also known under different name). Some clarification is needed. You can apply your custom sorting on various columns; moreover, you can have multiple viewing panes (windows) open sorted on different columns. Thus, the problem definition is a bit unclear.
Assuming that you know the sorting order in your viewing panes, then you can use System.IO.DirectoryInfo and derived FileSystemInfo[] objects; the latter has files.OrderBy method.
Hope this will help. My best, Alex
If you want natural sort order, you should either P/Invoke StrCmpLogicalW (http://msdn.microsoft.com/en-us/library/bb759947.aspx) or find a managed natural sort algorithm. There is no built-in natural sort in .NET Framework.
I think you cannot know which is the order in the pane (by size, name or whatever), you must read the list and then sort it the way you want or prompt the user to select a sorting attribute.
As Kenny posted Sorting Directory.GetFiles() here is an approach, anyway I still thinking there is no possibly way to know which is the sorting order that user selected in the viewing pane.
I think you would have to write a shell extension for windows explorer that captures sort events on columns and writes that metadata to disk in some structured way. You may have multiple explorer windows open so might be an idea to apply timestamp or id so you know which explorer window you are dealing with. Then in your app read that metadata to get the sort order and apply accordingly. Not easy but doable.

Categories

Resources