gpt4 book ai didi

c# - 获取带有文件夹路径的选定列表框值

转载 作者:行者123 更新时间:2023-11-30 12:48:33 24 4
gpt4 key购买 nike

我有一个列表框,它是用这种方法填充的,

private void ToReadFromExcel_Load(object sender, EventArgs e)
{
string folderpath = @"\\gibson\users";
// Call the method to show available files
PopulateListBox(ExcelListBox, folderpath, "*.csv");
}

// To populate list box with csv files from given path
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file.Name);
}
}

String strItem;
foreach (Object selecteditem in ExcelListBox.SelectedItems)
{
strItem = selecteditem as String;
MessageBox.Show(strItem);
}
// read csv file information and insert into detail table
string filepath = @"\\gibson\users\CampManager.csv";
StreamReader sr = new StreamReader(filepath);

我现在对文件路径进行了硬编码,但我需要传递在列表框中选择的文件路径。我在变量 stritem 中有文件名。如果我想传递整个文件夹路径,我该怎么做?

最佳答案

有一个理想的方法。您应该添加 FileInfo 对象本身,而不是添加 FileInfo 对象的 Name。所以稍后您将能够检索与该对象相关的任何信息,在您的情况下是大小、父文件夹等,而不仅仅是文件名。这样做:

// To populate list box with csv files from given path
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file); //<-- note here
}
}

String strItem;
foreach (FileInfo selecteditem in ExcelListBox.SelectedItems)
{
StreamReader sr = new StreamReader(selecteditem.FullName);
//or whatever
}

这里你应该注意的一件事是设置 DisplayMember ListBox 的属性如下:

ExcelListBox.DisplayMember = "Name";

它的作用是设置应该显示列表框中对象的什么属性。所以在这里你选择你想要的FileInfo.Name。这就是通常将自定义对象添加到 WinForms 中的列表框的方式。您通常不会只添加它的字符串部分。类似于 DisplayMember,还有 ValueMember 属性用于为每个对象分配一个值,可能是一些 id 左右,但在您的情况下没有。

一些建议,1) 如果您使用的是 .NET 4,则使用 EnumerateFiles而不是 GetFiles。前者是惰性的,只有在您开始枚举它们时(而不是事先)才会产生结果,因此它应该更快。

foreach (FileInfo file in dinfo.EnumerateFiles(FileType)) //<-- note here
{
lsb.Items.Add(file);
}

2) 使用 using 子句正确处理流阅读器,因为那样不会锁定您的文件。使用 using 始终是一个好习惯。比手动关闭和处理更护眼!像这样:

foreach (FileInfo selecteditem in ExcelListBox.SelectedItems)
{
using(StreamReader sr = new StreamReader(selecteditem.FullName))
{
//your code here
}
}

关于c# - 获取带有文件夹路径的选定列表框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13887816/

24 4 0
文章推荐: c# - .NET 3.5 中的 URL 重写
文章推荐: c# - 将 ThreadStatic 字段与任务一起使用
文章推荐: c# - 选择单元格时,如何突出显示 DataGrid 列标题和行标题?
文章推荐: c# - 将 List 添加到 EF