【发布时间】:2021-12-04 05:54:46
【问题描述】:
我正在尝试读取一个文件夹并查看文件名。使用此代码:
try
{
var folderPath = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";
foreach (string file in Directory.EnumerateFiles(Path.GetFileName(folderPath)))
{
var ha = file;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
很遗憾,我收到以下错误:
路径不合法
我的原始文件路径:
var folderPath = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";
为了找到坏字符,我写了这段代码:
string illegal = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
illegal = illegal.Replace(c.ToString(), "");
}
返回:
“CUsersGamersourcereposcarValLocalcarValLocalfiles”
这显然不是文件名。
如果我不使用 Path 类,它仍然会找到文件。我怎样才能使它工作,因为我尝试过的一切(比如删除非法字符)都不起作用。
【问题讨论】:
-
我想文件是一个目录。因此,从末尾删除 \ 字符以及 Path.GetFileName(folderPath)。如果要枚举文件夹路径中的文件,请使用
Directory.EnumerateFiles(folderPath) -
调试第一步:
Path.GetFileName(folderPath)实际返回了什么? - 不是“该文件夹中的所有文件”