微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个列表框,并通过此方法填充,

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 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
}

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

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
     }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐