0

如何访问 ListViewControl 中的文件?在初始事件中,我有一个按钮,它使用 foreach 循环在 lsitView 上列出了必要的文件。该控件有 2 项:文件名和文件路径(子项)

DirectoryInfo d = new DirectoryInfo(path);
foreach (FileInfo f in d.GetFiles("*.txt", SearchOption.AllDirectories))
{
    lstProjectFiles.Items.Add(f.Name).SubItems.Add(f.DirectoryName.ToString());
}      

现在,我想显示每个项目的完整路径以及带有扩展名的文件名。

foreach(ListViewItem f in lstView1.Items)
{
    Console.Writeline(f.ToString());
}

当我得到文件名时,输出如下所示。有额外的字符串,而不仅仅是 filename.extension:

列表视图项:{sample.txt}

4

2 回答 2

1

You are only loading the file name into the list box, not the FileInfo.

How about cheating a little and storing the FileInfo in the Tag property?

DirectoryInfo d = new DirectoryInfo(path);
foreach (FileInfo f in d.GetFiles("*.txt", SearchOption.AllDirectories))
{
    lstProjectFiles.Items.Add(f.Name).SubItems.Add(f.DirectoryName.ToString()).Tag = f; // Store FileInfo in Tag property
}

...

foreach(ListViewItem f in lstView1.Items)
{
    Console.Writeline(((FileInfo)f.SubItems[0].Tag).FullName);
}

Then you can access anything in the FileInfo object later on. Of course you may want to refactor & validate, but this is the gist of one approach you could take.

于 2013-11-12T01:04:12.247 回答
1

尝试这样的事情,它正在使用 SubItems Text Property

foreach (ListViewItem f in lstProjectFiles.Items)
{
    Console.WriteLine(f.SubItems[0].Text);
    Console.WriteLine(f.SubItems[1].Text);
}
于 2013-11-12T01:18:34.207 回答