在目录中生成文件名列表,修改文件名,但仍然能够访问完整路径winforms

时间:2019-04-09 19:14:42

标签: c# winforms file file-io

我正在使用C#和WinForms创建一个应用程序。我有一个代码,该代码以递归方式遍历目录以获取文件名。然后,我修改文件名,并在ListBox中显示修改后的名称。我的问题是我迷失了完整的道路。我需要保留完整路径以进行进一步处理,但不会显示在ListBox上。

foreach (string fileName in Directory.GetFiles(path))
{
    String displayedName = "";
    String fullPath = fileName;
    if (fileName.Contains("tsv"))
    {
        try
        {
            //make changes here
        }
        catch (Exception e)
        {
        }
    }
}

foreach (string directory in Directory.GetDirectories(path))
{
    FindFiles(directory);
}

1 个答案:

答案 0 :(得分:1)

这是我所谈论的例子。您应该能够将其合并到现有代码中,因为它只不过是创建一个类,将信息放入对象中,然后说明如何将其取回。只需在新项目中添加一个按钮和一个列表框,然后将此代码放在适当的位置即可。

  private void button1_Click(object sender, EventArgs e)
    {
        string DemoPath = @"D:\MyImages\MyPicture.jpg";

        string filestring = Path.GetFileName(DemoPath); //filename only
        string pathstring = Path.GetDirectoryName(DemoPath); //path only
        MyFileInfo nfo = new MyFileInfo(); //instantiate your object
        nfo.fileName = filestring; //fill the properties
        nfo.filePath = pathstring;
        listBox1.Items.Add(nfo); //add it to the listbox (only filename shows)
     }

    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        //cast the selected item back to the MyFileInfoType and get its filePath
        string pathFromSelection = (listBox1.SelectedItem as MyFileInfo).filePath;
        MessageBox.Show(pathFromSelection);
    }


class MyFileInfo
{
    public string fileName { get; set; }
    public string filePath { get; set; }

    public override string ToString()
    {
        //Here we tell the object to only display the filename
        return fileName;
    }
}