0

我是 C# 和编码的新手。如果我问的是一个愚蠢的问题,请原谅我。我第一次使用Directory.GetFiles()如下:

var savedfiles = Directory.GetFiles(@"C:\DiaryFiles");

现在,我有一个文本框,bunifuTextbox1我在其中写了一些文本“Amogh”,它是来自“C:\DiaryFiles”的文件名。然后我使用nameRepair()如下函数:

private string nameRepair(string suspectfile)
{
    return  @"C:\DiaryFiles\" + suspectfile + ".akb";
}

(.akb 是扩展名)。但是,当我尝试这样做时会出现问题:

foreach(string f in SavedFiles)
    if(f.Trim() == nameRepair(form.bunifuTextbox1.text).Trim())
    {
        //this code is not executed:(
    }
    else
    {
        //this part is executed
    }

条件if总是返回 false

我究竟做错了什么?

编辑:(我发布整个代码)

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;
    }       
}

我试图在运行时创建标签,并希望更改与文本框文本匹配的标签上的文本颜色。

你可以在这里看到整个项目:

https://drive.google.com/open?id=1q6eqiGvWnQYV7f_t8abG1cTwbVlUIqbm

4

1 回答 1

0

我不确定这是导致问题的原因。但我知道这是一个大到值得回答的问题,因为如果它现在没有导致你的问题,那么它会在未来给你带来一个问题。

字符串比较区分大小写。这意味着,在您的代码行中:

if(f.Trim() == nameRepair(form.bunifuTextbox1.text).Trim())

...您正在检查字符串是否完全相同,包括区分大小写。现在,我们知道您的 nameRepair 函数显式添加了一个路径:

return  @"C:\DiaryFiles\" + suspectfile + ".akb";

...所需要的只是让您的其他文件具有如下名称/路径:

c:\diaryfiles\********.akb

......你的比较是行不通的。

每当我看到 if (string == string) 比较时,除非它正在检查 "" 字符串,否则我将其视为等待中的错误。相反,你想要这样的东西:

if (stringA.Equals(stringB, StringComparison.OrdinalIgnoreCase))

...或类似的。看起来不太好;不过,也不存在可能的错误。

于 2018-05-09T15:48:59.607 回答