Question

I have list all item using foreach by its filename. Now, how can I add in the second column the path of each files listed in the first column? I have already add a column or collection on the properties.

    foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
    {
        string fileName = Path.GetFileName(filePath);
        listViewFiles.Items.Add(fileName);
    }
Was it helpful?

Solution

Try this:

// Set up List View
listViewFiles.View = View.Details;
listViewFiles.Columns.Clear();
listViewFiles.Columns.Add("File name");
listViewFiles.Columns.Add("File path");

// Populate with files and file paths
foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
{
    string fileName = Path.GetFileName(filePath);
    listView1.Items.Add(fileName).SubItems.Add(new FileInfo(fileName).DirectoryName);
}

EDIT:

Personally, I find it easier to instantiate a DirectoryInfo for this kind of thing, it populate lots of useful fields for you. So you could do:

DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.GetFiles(fileType, SearchOption.AllDirectories))
    listViewFiles.Items.Add(fi.Name).SubItems.Add(fi.DirectoryName);

OTHER TIPS

If you want to know how you can extract the path (without filename), create a FileInfo object and read out its DirectoryName property:

var fi = new FileInfo(filename);
var dir = fi.DirectoryName;

You can do:

foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
{
    string fileName = Path.GetFileName(filePath);
    string directoryName = Path.GetDirectoryName(filePath);
    listViewFiles.Items.Add(fileName, directoryName);
}

See the ListViewItem constructors for more info.

You can use the SubItems:

foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
{
    FileInfo fi = new FileInfo(filepath);        
    listViewFiles.Items.Add(fi.Name).SubItems.Add(fi.DirectoryName);
}

EDIT: I modify it to have filename and file directory

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top