Click here to Skip to main content
15,880,651 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello friends !!!!!

I have one folder with many txt files with filename 11111111111_a,11111111111_b,22222222_a,22222222_b
How can separate to 2 listboxes by last digit?

What I have tried:

C#
private void Form1_Load(object sender, EventArgs e)
{
	textBox1.Text = Form1.GetMACAddress();
	DirectoryInfo obj = new DirectoryInfo(@"C:\");
	DirectoryInfo[] folders = obj.GetDirectories();
	comboBox1.DataSource = folders;
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
	var comboBox = (ComboBox)sender;
	var directoryInfo = comboBox.SelectedValue as DirectoryInfo;
	if (directoryInfo == null) return;
	var filenames = Directory.GetFiles(directoryInfo.FullName);
	var shortFilenames = filenames.Select(x => Path.GetFileName(x)).ToList();
	
	listBox1.DataSource = shortFilenames;
	listBox2.DataSource = shortFilenames;
}
Posted
Updated 7-Aug-20 0:13am
v2
Comments
TheRealSteveJudge 7-Aug-20 6:04am    
What do the file names really look like?
Don't they have a file type e.g. 11111111111_a.txt?
Stm21 7-Aug-20 6:10am    
i have a machine that export log with this format not exactly 111111_a.txt
but the last 2 digits are always _a _b _c _e etc.
TheRealSteveJudge 7-Aug-20 6:18am    
5* for asking an understandable question!

Something like this should work:
C#
var fileNames = directoryInfo.EnumerateFiles()
    .Select(f => f.Name)
    .ToLookup(f => Path.GetFileNameWithoutExtension(f).LastOrDefault());

listBox1.DataSource = fileNames['a'];
listBox2.DataSource = fileNames['b'];
 
Share this answer
 
Comments
TheRealSteveJudge 7-Aug-20 6:15am    
5* for the generic approach!
Stm21 7-Aug-20 6:17am    
Thank you!!!!!!!!!!!!!
If your filenames are like this
e.g. 11111111111_a.txt or 11111111111_b.txt
LINQ will help you.
C#
listBox1.DataSource = shortFilenames.Where(x => Path.GetFileNameWithoutExtension(x).EndsWith("a")).ToList();
listBox2.DataSource = shortFilenames.Where(x => Path.GetFileNameWithoutExtension(x).EndsWith("b")).ToList();

BTW It is recommended to assign more meaningful names to your user interface items.
e.g. listBox1 does not mean anything.

You could name the listBoxes e.g. listBoxLogA, listBoxLogB, listBoxLogC etc.
 
Share this answer
 
v2
Comments
Stm21 7-Aug-20 6:17am    
Thank you!!!!!!!!!!!!!
TheRealSteveJudge 7-Aug-20 6:19am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900