zoukankan      html  css  js  c++  java
  • C#判断本地文件,网络文件是否存在是否存在

    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;
                }
            }
  • 相关阅读:
    读书笔记
    STL 笔记
    Centos8如何配置网桥
    命令集合
    shared_ptr给管理的对象定制析沟函数
    share_ptr指向的对象的析构动作在创建的时候被捕获
    优秀博客
    字符串单词翻转
    带权图的最短路径算法(Dijkstra,Floyd,Bellman_ford)
    生产者与消费者 c++实现
  • 原文地址:https://www.cnblogs.com/XL-Tommy/p/6728469.html
Copyright © 2011-2022 走看看