2

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.

3 Answers 3

6

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man, I'll use this one... Since your other answer returns strings.
@user1067461: It's not my answer :) I just edited it because it didn't have a period at the end. But thanks anyway.
3

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).

Comments

3

Use Path.GetFileName(string path).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.