I am a newbie in c# and coding. Please pardon me if I am asking a silly question. I first used Directory.GetFiles() as follows:
var savedfiles = Directory.GetFiles(@"C:\DiaryFiles");
Now, I have a textbox bunifuTextbox1 in which I write some text "Amogh" which is a file name from "C:\DiaryFiles". Then I am using a function nameRepair() which is as follows:
private string nameRepair(string suspectfile)
{
return @"C:\DiaryFiles\" + suspectfile + ".akb";
}
(.akb is an extension). But, problem occurs when I try to do this:
foreach(string f in SavedFiles)
if(f.Trim() == nameRepair(form.bunifuTextbox1.text).Trim())
{
//this code is not executed:(
}
else
{
//this part is executed
}
Condition for if is always returning false
What am I doing wrong?
Edit:(I am posting whole code)
foreach (string f in savedfiles)
{
this.label = new Label();
this.label.Location = new System.Drawing.Point(108, 36 + customLabels.Count * 26);
this.label.Name = f;
this.label.Text = (f.Replace(@"C:\DiaryFiles\","")).Replace(".akb", "");
this.label.Width = f.Length * 20;
this.label.BackColor = System.Drawing.Color.Black;
if(f.Trim() == nameRepair(form.bunifuTextbox1.text.Trim()))
{
this.label.ForeColor = System.Drawing.Color.Red;
}
else
{
this.label.ForeColor = System.Drawing.Color.White;
}
}
I tried to create labels at run time and want to change color of text on the labels which matches textbox text.
You can see the whole project here:
https://drive.google.com/open?id=1q6eqiGvWnQYV7f_t8abG1cTwbVlUIqbm
I'm not sure this is what's causing the problem. But I DO know that it's a problem big enough to deserve an answer, because if it's not causing your problem now, it'll cause one for you in the future.
String comparisons are case sensitive. Which means, in your line of code:
... you're checking to see if the strings are exactly the same, including a sensitivity to case. Now, we know that your nameRepair function is explicitly adding a path:
... all it takes is for your other file to have a name/path like:
... and your comparison's not going to work.
Whenever I see a if (string == string) comparison, unless it's checking for a "" string, I view it as a bug-in-waiting. Instead, you want something like:
... or similar. Doesn't look as nice; doesn't hold a possible bug, though, either.