各位:
.NET Framework 本省在設計的時候,他對於異常沒有完全做到拋出,這樣可能會有很多意想不到的問題。
比如
你在asp.net 應用程序中判斷文件是否存在,這個文件可能是一個共享路徑 ,比如: System.IO.File.Exists(//montaquehou-mis/share/a.file)
這個文件在資源管理器中可以訪問,但是在你的應用程序中一般不能訪問。這個時候File.Exists 會返回false,其實文件時存在的。
原因很簡單,ASP.NET 默認是本機的 ASPNET 用戶,這個用戶沒有訪問權限。
我們看一下File.Exists 的內部實現,(System.IO.FIle 類放在mocorlib.dll 里面,各位可以用類似reflector 之類的工具反編譯一下)
public static bool Exists(string path)
{
string[] textArray1;
try
{
if (path == null)
{
return false;
}
if (path.Length == 0)
{
return false;
}
path = Path.GetFullPathInternal(path);
textArray1 = new string[1];
textArray1[0] = path;
new FileIOPermission(1, textArray1, 0, 0).Demand(); //顯式的要求一個權限
return File.InternalExists(path);
}
catch (ArgumentException)
{
}
catch (NotSupportedException)
{
}
catch (SecurityException) //出現異常之后並沒有拋出
{
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
return false; //這就是你看到的false
}
{
string[] textArray1;
try
{
if (path == null)
{
return false;
}
if (path.Length == 0)
{
return false;
}
path = Path.GetFullPathInternal(path);
textArray1 = new string[1];
textArray1[0] = path;
new FileIOPermission(1, textArray1, 0, 0).Demand(); //顯式的要求一個權限
return File.InternalExists(path);
}
catch (ArgumentException)
{
}
catch (NotSupportedException)
{
}
catch (SecurityException) //出現異常之后並沒有拋出
{
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
return false; //這就是你看到的false
}