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

标签 c# .net visual-studio

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

A 路径 可能是这样的
C:\someFolderC:\someFolder\someFileC:\someFolder\someFile.jpg
我想检查给定的路径是文件还是文件夹,如果是文件,我想检查它是否真的存在。

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

最佳答案

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 块中,因为如果文件或文件夹不存在,它将引发异常。

关于c# - 检查给定路径的文件或文件夹是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270873/

相关文章:

c# - 有没有办法创建或更新 MongoDB 索引?

.net - 在 DocumentViewer 中显示多个固定文档,就好像它们是单个文档一样

c++ - Visual Studio 2013 编译成功但有明显错误

c# - 在我在同一进程中创建的所有其他线程死亡后停止线程

c# - 从 WCF 服务返回类型化数据集导致未找到 'xs:string'

c# - 基于对象参数的模拟方法返回

c# - 如何在 C# 中刷新表单?

c# - 缓存控制:无存储,必须重新验证未发送到 IIS7 + ASP.NET MVC 中的客户端浏览器

c# - 如何从 C# 以编程方式(即 F5)刷新 Windows 桌面?

c# - Windows Phone 8 - 本地化不工作