[英]Generate a list of filenames in a directory, modify the filename but still be able to access the full path winforms
I am creating an application using C# and WinForms.我正在使用 C# 和 WinForms 创建一个应用程序。 I have a code that recursively loops through the directory to get the file name.
我有一个代码,它递归地遍历目录以获取文件名。 I then modify the file name and display the modified name in a
ListBox
.然后我修改文件名并在
ListBox
显示修改后的名称。 My issue is that I lost the full path.我的问题是我丢失了完整路径。 I need to retain the full path for further processing but not displayed on the
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);
}
Here's an example of what I'm talking about.这是我正在谈论的一个例子。 You should be able to incorporate this into your existing code as it's nothing more than creating a class, putting the info into the object and then shows how to get it back.
您应该能够将其合并到您现有的代码中,因为它只不过是创建一个类,将信息放入对象中,然后展示如何将其取回。 Just add a button and a listbox to a new project and put this code in the appropriate places.
只需在新项目中添加一个按钮和一个列表框,然后将此代码放在适当的位置即可。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.