File.Exists 方法 (String)

确定指定的文件是否存在。

命名空间:   System.IO
程序集:  mscorlib(位于 mscorlib.dll)

参数

path
Type: System.String

要检查的文件。

返回值

Type: System.Boolean

如果调用方具有要求的权限并且 true 包含现有文件的名称,则为 path;否则为 false 如果 false 为 path(一个无效路径或零长度字符串),则此方法也将返回 null 如果调用方不具有读取指定文件所需的足够权限,则不引发异常并且该方法返回 false,这与 path 是否存在无关。

1、判断本地文件是否存在代码:

        static void Main(string[] args)
        {
string path = "C:/Users/lenovo/Desktop/test.jpg"; if (System.IO.File.Exists(path)) { Console.WriteLine("本地文件确实存在!"); } else { Console.WriteLine("本地文件不存在!"); } Console.ReadKey(); }

主要是通过System.IO.FIle对象的Exists方法来进行判断。

2、判断网络文件是否存在代码:

网络地址→请求对象→判断响应状态是否为200。

        static void Main(string[] args)
        {
            string url = @"https://www.baidu.com/test.png";//网络文件地址
            if (JudgeFileExist(url))
            { Console.WriteLine("网络文件确实存在!"); }
            else
            { Console.WriteLine("网络文件不存在!"); }
            Console.ReadKey();
        }
        private static bool JudgeFileExist(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;
            }
        }

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!