【问题标题】:How to select folder path from listview如何从列表视图中选择文件夹路径
【发布时间】:2018-01-15 10:41:55
【问题描述】:

我有一个带有文件夹的列表视图。我正在尝试从列表视图中获取选定文件夹的文件以将它们添加到列表框。

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    string filepath = Path.GetDirectoryName(listView1.SelectedItems);
    listBox1.Items.Add(filepath);
}

这就是我所拥有的,我知道这应该只将文件夹添加到列表框,但它只是将(集合)添加到列表框。

任何帮助将不胜感激。

编辑:按照@aria 的代码,我将Path.GetDirectoryName(listview1.SelectedItems[i].Text) 切换为Directory.GetFiles[i].Text),但现在它给了我一个错误。 System.IO.DirectoryNotFoundException: 'Could not find a part of the path 并且路径是项目的调试文件夹,而不是实际的文件夹路径。

为什么要转到调试文件夹?

【问题讨论】:

  • ListView.SelectedItems 返回一个集合类,所以我很确定当您尝试将集合传递给 Path.GetDirectoryName() 时,您的代码将会失败,这将期待 string跨度>
  • “它似乎不起作用。”是一个非常狭隘的问题描述。如果您尝试准确描述您获得的输出和/或您收到的错误消息,您真的可以帮助愿意帮助您的人
  • 我在这里有点困惑。 “从列表视图中选择的文件夹”所以您的列表视图包含文件夹?=!并且您想选择一个文件夹,然后获取其中的所有文件并将名称写入 ListBox1 ?对吗?
  • @MongZhu 是的,这正是我想要做的。抱歉我的描述,我对描述我的代码还是新手。
  • 只是名字......我是个白痴,因为没有看到。编辑:@MongZhu 我更改了列表视图的代码,现在列表框正在填充。谢谢你为我指出。

标签: c# listview


【解决方案1】:

正如他们的 cmets 提到的那样,SelectedItems 将为您提供 ListViewItem 的集合,因此您可以像这样迭代它们。

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
  if(listView1.SelectedItems.Count == 0) return;
  for(int i=0;i<=listView1.SelectedItems.Count-1;i++)
  {
      string filepath = Path.GetDirectoryName(listView1.SelectedItems[i].Text);
      listBox1.Items.Add(filepath);
  }
}

【讨论】:

  • 我试过了,但没有任何东西被添加到列表框中。没有文件或任何东西。
  • @MarcoAlba, TextlistView1.SelectedItems[i] 是什么,例如它应该类似于 `C:\Dir1\Dir2\`
  • 应该是`E:\Music\All Star`
  • 好的,现在我知道出了什么问题。我的文件夹中有两个文件。所以现在我添加了一个foreach (string adirs in filepath),它给了我System.IO.DirectoryNotFoundException: 'Could not find a part of the path的错误
  • @MarcoAlba,然后GetDirectoryName 给你`E:\Music`
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2012-06-06
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
相关资源
最近更新 更多