在文件盒 2 中使用文件框中的文件

本文关键字:文件 | 更新日期: 2023-09-27 18:36:54

我正在构建一些代码,可以从您当前位置加载所有文件并将它们显示在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);
    }

在文件盒 2 中使用文件框中的文件

您必须循环访问 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));
         }
     }
}