我正在嘗試讀取一個檔案夾并查看檔案名。使用此代碼:
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該類,它仍然會找到檔案。我怎樣才能做到這一點,因為我嘗試過的一切(比如洗掉非法字符)都不起作用。
uj5u.com熱心網友回復:
好吧,對于給定的檔案夾路徑
var folderPath = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";
現有呼叫
Path.GetFileName(folderPath);
回傳空字串:""因為
C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\
\ /|
--------------------- directory ------------------------ file
如果您想在其中查找檔案,C:\Users\Gamer\source\repos\carValLocal\carValLocal\files可以使用Path.GetDirectoryName:
foreach (string file in Directory.EnumerateFiles(Path.GetDirectoryName(folderPath)))
{
...
}
如果您想要某種路徑操作,請嘗試DirectoryInfo,例如讓我們在
C:\Users\Gamer\source\repos\carValLocal\carValLocal
代碼:
var folderPath = @"C:\Users\Gamer\source\repos\carValLocal\carValLocal\files\";
DirectoryInfo di = new DirectoryInfo(folderPath);
foreach (string file in Directory.EnumerateFiles(di.Parent.FullName)) {
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323417.html
