1

我是 C# 编程的新手。请建议我如何检索完整路径,但在我的代码中只使用 file.Name,因为我只想在我的 listBox 中输入文件名而不是完整路径

我的代码是:

listBox1.DataSource = GetFolder("..\\video\\");

private static List<string> GetFolder(string folder)
{
    List<string> FileList = new List<string>();

    var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg", 
                                                    SearchOption.AllDirectories)
    foreach (FileInfo file in allFiles)
    {
        FileList.Add(file.FullName);             
    }    

    return FileList;  
}
4

4 回答 4

1

如果我猜对了,您希望 FullPath 作为值,但只显示 FileName。为此,您可以使用FileInfo包含这两个值的 s 列表,并告诉 ListBox 哪个成员是值以及应该显示哪个成员:

this.listBox1.DisplayMember = "Name";
this.listBox1.ValueMember = "FullName";
listBox1.DataSource = GetFolder("..\\video\\");

Player.URL = Convert.ToString(listBox1.SelectedValue);  // Instead of SelectedItem

private static List<FileInfo> GetFolder(string folder)
{
    List<FileInfo> fileList = new List<FileInfo>();

    foreach (FileInfo file in new DirectoryInfo(folder).GetFiles("*.mpg", SearchOption.AllDirectories))
    {
       fileList.Add(file); 
    }    

    return fileList;  
}
于 2013-01-09T07:23:30.510 回答
1
FileInfo(path).Directory.FullPath

您的代码的实际问题是此行缺少分号

var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg", 
                                                    SearchOption.AllDirectories)

它应该是

var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg", 
                                                    SearchOption.AllDirectories);
于 2013-01-09T07:13:15.390 回答
0
 FileList.Add(file.FullName);

请像下面这样更改此行

 FileList.Add(file.Name );
于 2013-01-09T07:14:41.987 回答
0
  listBox1.DataSource = GetFolder("..\\video\\");

  private static List<string> GetFolder(string folder)
  {
        List<string> FileList = new List<string>();

        var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg", 
                                                SearchOption.AllDirectories)
        foreach (FileInfo file in allFiles)
        { 
              FileList.Add(file.Name);             
        }    

        return FileList;  
  }
于 2013-01-09T07:24:15.437 回答