[英]Directory.Exists(file) not working
string sourcePath = GetValue(key);
if (!Directory.Exists(@sourcePath))
{
throw new Exception("Source path in does not exist");
}
在調試中,查看text visualizer for sourcePath
返回文件的位置:
C:\\ Users \\ John \\ Desktop \\ Sales.dat
即使我知道飛行存在,這也會引發異常。 我可以在桌面上看到它,如果我將C:\\ Users \\ John \\ Desktop \\ Sales.dat粘貼到資源管理器中,則文件將打開。 請指教。
問題:您正在使用Directory.Exists()
方法檢查文件是否存在。
解決方案:您需要使用File.Exists()方法來檢查文件是否存在。
從MSDN:
File.Exists()方法確定指定的文件是否存在。
嘗試這個:
if (!File.Exists(@sourcePath))
{
throw new Exception("Source path in does not exist");
}
如果您想知道文件是否存在,那么File.Exists可能比Directory.Exists更好,后者會告訴您目錄是否存在。
如果您確實需要使用Directory.Exists()
,則可以執行以下操作:
if(!Directory.Exists(new FileInfo(sourcePath).DirectoryName))
{
throw new Exception("Source path in does not exist");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.