Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming all strings from an array in c#

I used this code to get the contents of a directory:

string[] savefile = Directory.GetFiles(mcsdir, "*.bin");
comboBox1.Items.AddRange(savefile);

and it returns as

C:\Users\Henry\MCS\save1.bin
C:\Users\Henry\MCS\save2.bin

How can I make it return as only

save1.bin
save2.bin

Please note that this app will be used by other people, so the name is not always "Henry". Thank you.

like image 851
user1067461 Avatar asked Jan 28 '26 06:01

user1067461


2 Answers

I would recommend using DirectoryInfo.GetFiles instead, and LINQ:

FileInfo[] savefile = new DirectoryInfo(mcsdir).GetFiles("*.bin");
comboBox1.Items.AddRange(savefile.Select(x => x.Name).ToArray());
like image 136
Ry- Avatar answered Jan 30 '26 20:01

Ry-


Use LINQ:

var strs = savefile.Select(a => Path.GetFileName(a)).ToArray();

Looking at the suggestion of minitech: As long as you get the array of type FileInfo[] there is no need to convert it to string array. Just set the property DisplayMember to the property name you want to display in your ComboBox.

FileInfo[] savefile = new DirectoryInfo(mcsdir).GetFiles("*.bin");
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = savefile;

Using this you keep your original FileInfo[] array with all additional information (as to the full path to your files) and same time display only the short filenames (without path) in your control.

(I assume that your question is about WinForms. If you are using Silverlight or WPF you need to set the property using the "Target" attribute).

like image 28
Alexander Galkin Avatar answered Jan 30 '26 19:01

Alexander Galkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!