我是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;
}
答案 0 :(得分:1)
FileInfo(path).Directory.FullPath
您的代码的实际问题是缺少此行的分号
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
应该是
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories);
答案 1 :(得分:1)
如果我说得对,你想要FullPath作为值,但只显示FileName。要实现这一点,您可以使用包含这两个值的FileInfo
列表,并告诉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;
}
答案 2 :(得分:0)
FileList.Add(file.FullName);
请更改此行,如下所示
FileList.Add(file.Name );
答案 3 :(得分: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;
}