检查给定路径下的文件或文件夹是否存在

3
我正在让用户将路径作为字符串传递。
一个“路径”可能是这样的
C:\someFolder C:\someFolder\someFile C:\someFolder\someFile.jpg
我想检查给定的路径是文件还是文件夹,如果是文件,我想检查它是否存在。
我一直在使用FileAttributes fileRoot = File.GetAttributes(@path);来检查它是文件还是文件夹,但它并不能正常工作。

1
我认为fileAttributes可以正确地识别文件或目录。你能告诉我为什么它不能正常工作吗? - jadavparesh06
问题是重复的,下次请至少在SO中搜索! https://dev59.com/wHM_5IYBdhLWcg3wZSPX?lq=1 - mybirthname
@mybirthname,我看了那个问题。它没有提到文件可能不存在的情况。 - anon
5个回答

11
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\";
            FileAttributes attributes = File.GetAttributes(path);

            switch (attributes)
            {
                case FileAttributes.Directory:
                    if (Directory.Exists(path))
                        Console.WriteLine("This directory exists.");
                    else
                        Console.WriteLine("This directory does not exist.");
                    break;
                default:
                    if (File.Exists(path))
                        Console.WriteLine("This file exists.");
                    else
                        Console.WriteLine("This file does not exist.");
                    break;
            }
        }
    }
}

这是我为您编写的一个可用示例。它获取path变量,确定它是目录还是文件,然后检查它是否存在。只需确保适当处理FileAttributes attributes = File.GetAttributes(path);行,例如将其放置在try / catch块中,因为如果文件或文件夹不存在,则会引发异常。


感谢您的快速和完整的回答。 - anon
非常感谢。只需确保适当处理 FileAttributes attributes = File.GetAttributes(path); 这一行,例如将其放置在 try/catch 块中,因为如果文件或文件夹不存在,它将抛出异常。 - jay_t55
哈,是的,我刚刚意识到了。 - anon
抱歉哈哈,我应该在我的回答中包含那个。 - jay_t55

4
    static void Main(string[] args)
    {
        string Path = @"C:\Abhishek\Documents";
        string filePath = @"C:\Abhishek\Documents.txt";
        bool isDirExists = Directory.Exists(Path);
        bool isFileExists = File.Exists(filePath);

        if (isDirExists)
        {
            Console.WriteLine("Directory Exists");
        }
        else {
            Console.WriteLine("Directory does not exists");
        }
        if (isFileExists)
        {
            Console.WriteLine("File Exists");
        }
        else
        {
            Console.WriteLine("File does not exists");
        }
        Console.ReadKey();
    }

2
这并没有解决原帖作者的问题。这需要您事先知道字符串是目录还是文件。 - jay_t55
@jay_t55 这是正确的做法,得到赞成的答案并不适用于每种情况!他只需要检查一个字符串即可... - mybirthname
是的,但有可能存在同名的目录和文件。 - Abhishek

2
您可以使用File.Exists检查文件是否存在。
您可以使用Directory.Exists检查文件夹是否存在。
然后,您可以使用这个来检查它是一个文件还是文件夹。
private bool CheckIfExists(string path)
{
    // get the file attributes for file or directory
    FileAttributes attr = File.GetAttributes(path);

    //detect whether its a directory or file
    if((attr & FileAttributes.Directory) == FileAttributes.Directory)
        return Directory.Exists(path);
    else
        return File.Exists(path);
}

谢谢你的回答。我尝试了这个方法,但是对于文件夹不起作用。它只是简单地说“不存在”。 - anon
@john 使用 Directory.Exists 来判断文件夹是否存在。 - David Pilkington
我明白了,谢谢,我会去查看的。 - anon

0
请你能否澄清这个陈述:
但它不能正常工作。
"不正常" 的情况有哪些?
关于问题:
你的任务是否需要知道是文件还是目录?
如果不需要(即只想在文件存在时返回 "true"),你可以使用 File.Exists 并获得所需结果。 如果你担心会抛出异常,不用担心,这种情况下不会。
var filePath = @"d:\Storage\Repo\Detrack\Detrack.bak";
var dirPath = @"d:\Storage\Repo\Detrack\";
var dirPathWithoutTrailingSlash = @"d:\Storage\Repo\Detrack";

Console.WriteLine("Path ({0}) exists = {1}", filePath, new FileInfo(filePath).Exists);
Console.WriteLine("Path ({0}) exists = {1}", dirPath, new FileInfo(dirPath).Exists);
Console.WriteLine("Path ({0}) exists = {1}", dirPathWithoutTrailingSlash, new FileInfo(dirPathWithoutTrailingSlash).Exists);
Console.ReadLine();

结果如下:

Path (d:\Storage\Repo\Detrack\Detrack.bak) exists = True
Path (d:\Storage\Repo\Detrack\) exists = False
Path (d:\Storage\Repo\Detrack) exists = False

我之前不知道exists有两种检查方式——Directory.ExistsFile.Exists,因此我得到了错误的结果,以为代码没有正确运行。对此我感到很抱歉。 - anon

0
您可以使用以下代码进行检查:
// get the file attributes for file or directory
        FileAttributes attr = File.GetAttributes(@"c:\Temp");

        //detect whether its a directory or file
        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
        {
            // Its a directory
            // Do something here
        }
        else
        {
            // Its a file
            // Do something here
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接