获取路径中所有文件的名称

时间:2014-05-15 20:01:44

标签: c#

当我尝试从指定路径读取文件时,我收到错误访问路径...被拒绝。演示错误的代码如下:

string path = "D:\\Study\\Прога 4 семестр\\Курсач\\tests";
StreamReader sr = new StreamReader(path);
while(!sr.EndOfStream)
{
    string s = Path.GetFileNameWithoutExtension(path);
    listBox1.Items.Add(s);
}
sr.Close();

发生错误的代码究竟出了什么问题?我如何实现目标?

3 个答案:

答案 0 :(得分:4)

使用Directory.EnumerateFiles获取目录中的所有文件,然后将每个文件路径投影到文件名:

var names = Directory.EnumerateFiles(path)
                     .Select(f => Path.GetFileNameWithoutExtension(f));

甚至更短的方式:

Directory.EnumerateFiles(path).Select(Path.GetFileNameWithoutExtension);

答案 1 :(得分:2)

不幸的是你使用了错误的语法。 StreamReader将读取文件,它不会检索文件。您应该使用Directory中的System.IO功能。

示例:

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] files = Directory.GetFiles(path);
foreach(string item in files)
     Console.WriteLine(item);

这实际上会检索文件数据。

第二个例子:

 var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
 var file = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
      .Select(Path.GetFileName);

Microsoft Developer Network有一些关于处理系统中文件或目录检索的不同方法的文章。

答案 2 :(得分:0)

您可以使用Directory方法GetFiles(String) (+ 2 overloads)来枚举和处理旧版.NET Framework上的文件。

string path = "D:\\Study\\Прога 4 семестр\\Курсач\\tests";
string[] fileNames = Directory.GetFiles(path);
for(int i  = 0; i < fileNames.Length; i++)
{
    string fileName = Path.GetFileNameWithoutExtension(path + "\\" + fileNames[i]);
    listBox1.Items.Add(fileName);
}
相关问题