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

3 .net c# visual-studio

我让用户将路径作为字符串传递。

一条路径可能是这样的

C:\someFolder

C:\someFolder\someFile

C:\someFolder\someFile.jpg

我想检查给定的路径是文件还是文件夹,如果是文件,我想检查它是否真的存在。

我一直在FileAttributes fileRoot = File.GetAttributes(@path);用来检查它是一个文件还是一个文件夹,但它不能正常工作。

jay*_*t55 7

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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