Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用文件夹路径获取选定列表框值的步骤_C# - Fatal编程技术网

C# 使用文件夹路径获取选定列表框值的步骤

C# 使用文件夹路径获取选定列表框值的步骤,c#,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

我有一个列表框,它由这个方法填充

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
}
ExcelListBox.DisplayMember = "Name";
这样做的目的是设置listbox中对象应显示的属性。因此,在这里您可以选择所需的
FileInfo.Name
。这就是通常在WinForms中将自定义对象添加到列表框的方式。通常情况下,您不会只添加其中的字符串部分。与
DisplayMember
类似,还有一个
ValueMember
属性,用于为每个对象分配一个值,可能是某个id左右,但在您的情况下没有

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

foreach (FileInfo file in dinfo.EnumerateFiles(FileType)) //<-- note here
{
    lsb.Items.Add(file); 
}
foreach (FileInfo selecteditem in ExcelListBox.SelectedItems)
{
     using(StreamReader sr = new StreamReader(selecteditem.FullName))
     {
         //your code here
     }
}