1

我正在构建一些代码,从您当前的位置加载所有文件并将它们显示在 listbox1 中。然后在第二个列表框中,我想获取在 listbox1 中加载的所有文件的文件大小。到目前为止,代码会返回文件夹内所有文件的文件大小。

到目前为止,这是我的代码:

    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);
    }
4

1 回答 1

0

您必须遍历 中的项目ListBox1,从文件路径创建FileInfo变量并将您希望的信息添加到其他列表框。示例代码:

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));
         }
     }
}
于 2013-10-26T11:07:54.413 回答