判斷文件存在狀態應用比較廣泛,包括判斷本地文件和網絡文件是否存在,本質都是通過請求文件的返回狀態來判斷,判斷文件之後再根據不同情況來分別處理,比如會員系統的頭像,就需要來判斷會員信息是否包含圖片,有就顯示,沒有就要顯示默認圖片。
工具/原料
測試內容的程序文件
方法/步驟
判斷本地文件是否存在代碼:
//本地文件
string path = "C:/Users/lenovo/Desktop/temp/1.jpg";
if (System.IO.File.Exists(path))
{ Console.WriteLine("本地文件確實存在!"); }
else
{ Console.WriteLine("本地文件不存在!"); }
主要是通過System.IO.FIle對象的Exists方法來進行判斷。
判斷網絡文件是否存在的邏輯思路,就是根據網絡地址創建請求對象,然後獲取請求對象的響應狀態,判斷響應代碼是否是200,最後成功的就說明圖片存在,反之就沒有。不同於本地文件直接通過文件流來判斷的方式。
判斷本地文件是否存在方式一代碼:
//方式一
string url="";//網絡文件地址
if (JudgeFileExist01(url) == 1)
{ Console.WriteLine("01網絡文件確實存在!"); }
else
{ Console.WriteLine("01網絡文件不存在!"); }
//調用方法:
private static int JudgeFileExist01(string url)
{
//判斷網絡地址存在
if (url.Length > 1)
{
//創建根據網絡地址的請求對象
System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(url));
System.Net.ServicePointManager.Expect100Continue = false;
try
{
//響應對象的成功狀態
((System.Net.HttpWebResponse)httpWebRequest.GetResponse()).Close();
}
catch (System.Net.WebException exception)
{
if (exception.Status != System.Net.WebExceptionStatus.ProtocolError)
{ return 1; }
if (exception.Message.IndexOf("500") > 0)
{ return 500; }
if (exception.Message.IndexOf("401") > 0)
{ return 401; }
if (exception.Message.IndexOf("404") > 0)
{ return 404; }
}
}
return 1;
}
判斷本地文件是否存在方式二代碼:
//方式二
string url="";//網絡文件地址
if (JudgeFileExist02(url))
{ Console.WriteLine("02網絡文件確實存在!"); }
else
{ Console.WriteLine("02網絡文件不存在!"); }
//調用方法:
private static bool JudgeFileExist02(string url)
{
bool res = false;
//響應對象
System.Net.WebResponse webResponse = null;
try
{
//創建根據網絡地址的請求對象
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url);
//獲取請求對象的響應狀態
webResponse = webRequest.GetResponse();
//判斷響應對象內容
res = webResponse == null ? false : true;
}
catch (Exception ex)
{ res = false; }
finally
{
if (webResponse != null)
{ webResponse.Close(); }
}
return res;
}
判斷本地文件是否存在方式三代碼:
//方式三
string url="";//網絡文件地址
if (JudgeFileExist03(url))
{ Console.WriteLine("03網絡文件確實存在!"); }
else
{ Console.WriteLine("03網絡文件不存在!"); }
//調用方法:
private static bool JudgeFileExist03(string url)
{
try
{
//創建根據網絡地址的請求對象
System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.CreateDefault(new Uri(url));
httpWebRequest.Method = "HEAD";
httpWebRequest.Timeout = 1000;
//返回響應狀態是否是成功比較的布爾值
return (((System.Net.HttpWebResponse)httpWebRequest.GetResponse()).StatusCode == System.Net.HttpStatusCode.OK);
}
catch
{
return false;
}
}
注意事項
應該考慮文件判斷的情況,尤其是網絡文件的判斷方式。