【问题标题】:Adding multiple filenames to listBox, but without extensions? C#向 listBox 添加多个文件名,但没有扩展名? C#
【发布时间】:2011-11-04 22:23:09
【问题描述】:

我正在编写一个将可执行文件添加到 C# 中的列表框的程序。

我正在尝试将项目添加到不带 .exe 扩展名的列表框中。这是我之前的代码:

listBox1.Items.Add(openFiles.SafeFileNames.Replace(".exe",""));

它运行良好,但它不支持多个文件。当代码在选择多个项目而不是一个项目后运行时,它会添加项目“System.String[]”(这不好!D:)

我能得到一些帮助吗?我会试着解释得更好一点,我没有睡太多,所以我可能有点漫无目的 -

我想同时将多个文件添加到我的列表框中,我的 openFileDialog 设置为 multiSelect = true,但不包括文件扩展名 (.exe) 与单个项目一起输入到列表框中。

如果这不能轻松完成,我将切换回单选。

【问题讨论】:

  • 您确定没有像my.executor.exe 这样的文件名吗?因为您的代码会将其更改为mycutor,而不是my.executor
  • 我不会担心的。 :S

标签: c# winforms listbox openfiledialog file-extension


【解决方案1】:

我认为你需要做一个循环,从返回的数组中的每个文件名中删除“.exe”:

foreach (string fileName in openFiles.SafeFileNames)
{
    listBox1.Items.Add(fileName.Replace(".exe",""));
}

【讨论】:

    【解决方案2】:

    使用System.IO.Path.GetFileNameWithoutExtension(file) 方法。

    编辑:

    foreach (string FileName in openFiles.SafeFileNames)
      {
        listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(FileName));
      }
    

    【讨论】:

    • 完美运行!非常感谢!
    【解决方案3】:

    使用 FileInfo 类。它具有带扩展名和不带扩展名的名称,以及整个目录名和文件名。 MSDN FileInfo

    【讨论】:

      猜你喜欢
      • 2012-12-24
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 2014-03-07
      • 2022-12-19
      • 2012-01-18
      • 2012-10-07
      • 2016-09-06
      相关资源
      最近更新 更多