求C#判断文件名能否存在函数

.Net技术 码拜 8年前 (2016-02-29) 1327次浏览
1.求file.Exists内部实现源码

2.求判断含有空格的文件路径名能否存在源码?
两者选其一
解决方案

2

File.Exists源码,你反编译下.net类库的对应dll呗

8

2

其实看这源码并没有什么实用意义。
直接使用文件名能否存在并遍历能否存在空格就行了。当然假如类库存在模糊匹配函数可以直接使用。

1

求C#判断文件名能否存在函数 懒死你

10

求C#判断文件名能否存在函数
Console.WriteLine(File.Exists(“123 456.txt”)); //True
有什么问题吗?

17

引用 5 楼 z84616995z 的回复:
Quote: 引用 3 楼 zhi_ai_yaya 的回复:

其实看这源码并没有什么实用意义。
直接使用文件名能否存在并遍历能否存在空格就行了。当然假如类库存在模糊匹配函数可以直接使用。

确实  所以本人想问:有没有办法实现  判断文件能否存在时允许文件名包含空格的方法

    class Program
    {
        static void Main(string[] args)
        {
            string s = @"F:\主机  型号.txt";
            bool rt = File.Exists(s);
            Console.WriteLine("{0} is {1}", s, rt ? "存在" : "不存在");
           Console.ReadKey();   
        }
    }
//output
F:\主机  型号.txt is 存在

搜索指定目录下文件名包含空格的文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = @"F:\主机  型号.txt";
           // bool rt = File.Exists(s);
           // Console.WriteLine("{0} is {1}", s, rt ? "存在" : "不存在");
           //Console.ReadKey();
           string path = @"F:";
           string filter = "* *"; //使用通配符,两个*号之间包含一个空格,即可搜索包含空格的文件名
           PrintFileSystemEntries(path, filter);
           Console.ReadKey();
 
        }
        static void PrintFileSystemEntries(string path, string pattern)
        {
            try
            {
                // Obtain the file system entries in the directory
                // path that match the pattern.
                string[] directoryEntries =
                    System.IO.Directory.GetFileSystemEntries(path, pattern);
                foreach (string str in directoryEntries)
                {
                    System.Console.WriteLine(str);
                }
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, " +
                    "or contains invalid characters.");
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                System.Console.WriteLine("The path encapsulated in the " +
                    "Directory object does not exist.");
            }
        }
    }
}

https://msdn.microsoft.com/zh-cn/library/d3eayw32%28v=vs.110%29.aspx


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明求C#判断文件名能否存在函数
喜欢 (0)
[1034331897@qq.com]
分享 (0)