Search code examples
c#dictionaryfileinfo

How to display information about SelectedFile


I am trying to get information about selected files and list their properties (such as name and length) in a ListBox, but I couldn't figure out how to do it. I wrote this code, but it doesn't meet my expectations. How can I do this with a DictionaryList?

private void button1_Click(object sender, EventArgs e)
{
    FileInfo fi = null;
    // Dictionary<string, int> info = new Dictionary<string, int>();
    openFileDialog1.Multiselect = true;
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {

        foreach (string file in openFileDialog1.FileNames)
        {
            listBox1.Items.Add(fi = new FileInfo(file));

        }
    }
}

Solution

  • Try pulling out some members of the FileInfo class to display in your ListBox. Change

    listBox1.Items.Add(fi = new FileInfo(file));
    

    to

    var info = new FileInfo(file);
    listBox1.Items.Add(String.Format("Filename: {0} Size: {1}", info.Name, info.Length));
    

    As for using a Dictionary, you could define a dictionary somewhere:

    Dictionary<string,FileInfo> fileInfoDictionary = new Dictionary<string,FileInfo>();
    

    Then add your FileInfo objects into it:

    foreach (string file in openFileDialog1.FileNames)
    {
        fileInfoDictionary[file] = new FileInfo(file);
    }
    

    And then at some later point use the information (without having to go out to the filesystem again):

    Console.WriteLine(fileInfoDictionary[@"c:\autoexec.bat"].Length);
    

    The line right there would display the filesize of autoexec.bat, if it existed. If not, that line would throw a KeyNotFoundException.

    Alternatively, if all you cared about was file size, you could declare your dictionary like you have in your own post:

    Dictionary<string,int> fileSizeDict = new Dictionary<string,int>();
    // ...
    fileSizeDict[file] = new FileInfo(file).Length;
    // ...
    Console.WriteLine(String.Format("The length of autoexec.bat is {0}", fileSizeDict["@c:\autoexec.bat"]));