Directory.Exists(文件)无法正常工作

Joh*_*ohn 0 c# directory asp.net-mvc asp.net-mvc-3

string sourcePath = GetValue(key); 

if (!Directory.Exists(@sourcePath))
{
    throw new Exception("Source path in does not exist");
}
Run Code Online (Sandbox Code Playgroud)

在调试中,查看文本可视化工具以sourcePath返回文件的位置:

C:\用户\约翰\桌面\ Sales.dat

即使我知道flie存在,这也会引发异常.我可以在桌面上看到它,如果我将C:\ Users\John\Desktop\Sales.dat粘贴到资源管理器中,则会打开该文件.请指教.

Sud*_*udi 5

问题:您正在使用该Directory.Exists()方法检查文件是否存在.

解决方案:您需要使用File.Exists()方法来检查文件是否存在.

来自MSDN:

File.Exists()方法确定指定的文件是否存在.

试试这个:

if (!File.Exists(@sourcePath))
{
    throw new Exception("Source path in does not exist");
}
Run Code Online (Sandbox Code Playgroud)