How to get list of .xlsx file in C# - 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

Related

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.

Conditional file listing on gridView in ASP.NET?

I am writing a file management web page for a friend of mine. I select the folder using a DropDownlist element. When the index changed it populates gridview.
For preventing user slips, I have decided not to delete the file when Delete button is clicked. I change the name of the deleted file adding a suffix.
For example if I delete a file.pdf via Deletebutton, it is renamed as file.pdf_zkanoca_deleted_1411472294
After populating the gridview content, renamed files are still listed. My listFiles() method is as the following:
public void listFiles(string selectedFolder)
{
var dir = new DirectoryInfo(selectedFolder);
gridView1.DataSource = dir.GetFiles();
gridView1.DataBind();
}
What I want is to check whether filename contains "_zkanoca_deleted_" string before binding data source to gridview. If it contains that string it will not be listed.
I think a foreach loop will solve my problem. But I could not imagine how to structure it.
Use the IEnumerable.Where extension
gridView1.DataSource = dir.GetFiles().Where(x => !x.Name.Contains("_zkanoca_deleted_")).ToList();
As explained in the docs the Where extension filters a sequence using a predicate.
In this case you could use the FileInfo property Name to check if it contains the forbidden substring and exclude that FileInfo from the sequence binded to the gridview.

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.

Sharepoint SPFile - Get File Type

I am using SPFile to display a list of files and I want to display the type of file, as a string, so PDF, Word, Excel etc.
Looks like:
FileABC PDF
FileDEF Excel
I have got the icon back using "ListItem.File.IconUrl", ListItem is SPListItem
But I would like to get the file type as a name. It must work out the file type so the correct image can be displayed but I want to display the words too (for accessibility)
You can simply take the "FileLeafRef" attribute which contains filename + local path, create an System.IO.FileInfo object out of that and then access the .Extension property:
System.IO.FileInfo inf = new System.IO.FileInfo("/images/files/something.gif");
Console.WriteLine(inf.Extension); //outputs .gif
I believe it will not be that easy to find matching program for each extension (you mention you need "Excel" not "xls". So, the easiest way, i think, is to create a dictionary of known extensions. Something like this:
System.Collections.Specialized.StringDictionary oDict = new System.Collections.Specialized.StringDictionary();
oDict.Add(".xls", "Excel");
oDict.Add(".xlsx", "Excel");
oDict.Add(".doc", "Word");
and then:
oDict[inf.Extension]
You can get the extension from the listitem as
ListItem[SPBuiltInFieldId.DocIcon]

Categories

Resources