Reputation: 73
I have two listboxes with several data, ListBox1 have this format:
C:\Users\Charlie\Desktop\Trials\Trial0004COP.txt
and in my ListBox2:
Trial0004COP
How can I check if Trial0004COP exists in my listbox1? I used Contain() but it doesn't work.
Upvotes: 0
Views: 304
Reputation: 680
I would recommend something like:
var searchString = "Trial0004COP";
var isFound = false;
foreach(var name in listbox1.items)
{
if (Path.GetFileNameWithoutExtension(name).ToLower() == searchString.ToLower())
{
_IsFound = true;
break;
}
}
Note that in Windows, file names are case-preserving but not case-sensitive, so you need to check the file name ignoring its case.
You could do it in a single line in Linq, if that's your thing.
var searchString = "Trial0004COP";
var isFound = listBox1.Items.Cast<string>()
.Any(x => Path.GetFileNameWithoutExtension(x).ToLower() == searchString.ToLower());
Upvotes: 1
Reputation: 13020
Using LINQ you can do:
listBox1.Items.Select(e => Path.GetFileNameWithoutExtension(e as string)).Contains("Trial0004COP");
Upvotes: 0
Reputation: 16623
What about:
bool found = listBox1.Items.Cast<string>()
.Where(x => x.Contains("Trial0004COP"))
.Any();
Or to make it more accurate use String.EndsWith()
method but you also have to add ".txt"
if you want to make it works:
bool found = listBox1.Items.Cast<string>()
.Where(x => x.EndsWith("Trial0004COP.txt"))
.Any();
Edit :
Hi Fuex, I'm using OpenFileDialog to select a file, then this file is added to my listbox1 with all the Directory name. In my listbox2 I read another file that contains several Trials000""" and add them to it, I want to know if the file that I selected from the open dialog exist in my listboz2
Yes can do it in this way:
bool found = false;
if(openFileDialog.ShowDialog() == DialogResult.OK){
found = listBox.Items.Cast<string>()
.Where(x => x.EndsWith(openFileDialog.FileName))
.Any();
if(!found)
MessageBox.Show(openFileDialog.FileName + " doesn't exist in listBox1"); //show a message
}
Upvotes: 0