加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用文件夹路径获取所选列表框值

发布时间:2020-12-15 21:44:19 所属栏目:百科 来源:网络整理
导读:我有一个列表框,并通过此方法填充, private void ToReadFromExcel_Load(object sender,EventArgs e){ string folderpath = @"gibsonusers"; // Call the method to show available files PopulateListBox(ExcelListBox,folderpath,"*.csv");}// To popula
我有一个列表框,并通过此方法填充,

private void ToReadFromExcel_Load(object sender,EventArgs e)
{
    string folderpath = @"gibsonusers";
    // 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 = @"gibsonusersCampManager.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 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
}

你应该注意的一件事是设置ListBox的DisplayMember属性,如下所示:

ExcelListBox.DisplayMember = "Name";

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

很少有建议,1)如果你使用的是.NET 4,那么使用EnumerateFiles而不是GetFiles.前者是懒惰的,只有当你开始枚举它们时才产生结果(不是事先),所以它应该更快.

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读