I am building some code that loads all files from your current location and shows them in listbox1 . Then in the second listbox I want to get the filesize of all files that were loaded in listbox1 . As of now the code gives back the filesize of all files inside the folder .

Here is my code so far :

    private void button1_Click(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(".");          
        FileInfo[] Files = dinfo.GetFiles("*.xml");
        foreach (FileInfo file in Files)
        {
            listBox1.Items.Add(file.Name);
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(".");   
        FileInfo[] Files = dinfo.GetFiles("*.xml");
        foreach (FileInfo file in Files)
        {
            listBox2.Items.Add(DecToHex(file.Length));
        }

        string filename = "original.txt";
        string listboxData = "";
        foreach (string str in listBox2.Items)
        {
            listboxData += str + "\n ";
        }

        File.WriteAllText(filename, listboxData);
    }

    private void button3_Click(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(".");   
        FileInfo[] Files = dinfo.GetFiles("*.xml");
        foreach (FileInfo file in Files)
        {
            listBox3.Items.Add(DecToHex(file.Length));
        }

        string filename = "changed.txt";
        string listboxData = "";
        foreach (string str in listBox3.Items)
        {
            listboxData += str + "\n ";
        }

        File.WriteAllText(filename, listboxData);
    }
有帮助吗?

解决方案

You have to iterate through the items in ListBox1, create the FileInfo variables from the file paths and add the information you wish to the other ListBoxes. Sample code:

string curDir = Environment.CurrentDirectory;  //By assuming that ListBox1 stores just file names and that the target directory is the one where the application is located 
foreach (string item in listBox1.Items)
{
     if (item != null && item.Trim().Length > 0)
     {
         string curPath = curDir + @"\" + item;
         if (File.Exists(curPath))
         {
             FileInfo file = new FileInfo(curPath);
             listBox2.Items.Add(DecToHex(file.Length));
         }
     }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top