【问题标题】:Directory.GetFiles errorDirectory.GetFiles 错误
【发布时间】:2016-03-01 18:29:36
【问题描述】:

我的代码

private void m1()
{
    List<string> list = new List<string>();

    foreach (string str in Directory.GetFiles("a1"))
    {
        if (Path.GetExtension(str).Contains("txt")) -- get all txt file in a1 folder
        {
            list.Add(Path.GetFileNameWithoutExtension(str));
        }
    }

    base.SuspendLayout();
    this.Combobox_1.Items.AddRange(list.ToArray());
    base.ResumeLayout();
}

但组合框无法列出文件夹 a1 中的 txt 文件 请帮帮我。

【问题讨论】:

  • 您确定“a1”的相对路径正确吗?
  • 您是否遇到了某种错误?还是只是没有加载组合框?
  • “但是组合框无法列出文件夹 a1 中的 txt 文件”是什么意思?会发生什么?
  • 您可以使用调试器检查list 是否至少已填充...
  • a1 文件夹应该在执行进程的工作目录中。当您通过双击或按 F5 或 CTRL + F5 启动可执行文件时,这与您的可执行文件所在的文件夹相同。是吗?您可以使用 string fullPathToA1Folder = System.IO.Path.GetFullPath("a1"); 检查实际位置

标签: c# c#-4.0


【解决方案1】:

我认为没有必要先将值存储在列表中,然后再添加到组合框中。 可以直接在组合框上完成。

我已将相对路径 a1 替换为真实路径,以便您轻松理解。

foreach (string str in Directory.GetFiles(@"D:\")) 
            {
                if (System.IO.Path.GetExtension(str).Contains("txt"))
                {
                    this.Combobox_1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(str));
                }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多