当我尝试从指定路径读取文件时,收到错误消息Access to the path ... is denied。演示错误的代码如下:
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();
发生错误的代码到底是哪里出了问题?我如何实现我的目标?
最佳答案
使用Directory.EnumerateFiles获取目录中的所有文件,然后将每个文件路径投影到文件名:
var names = Directory.EnumerateFiles(path)
.Select(f => Path.GetFileNameWithoutExtension(f));
或者更短的方式:
Directory.EnumerateFiles(path).Select(Path.GetFileNameWithoutExtension);
关于c# - 获取路径中所有文件的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23687573/