我让用户将路径作为字符串传递。
A 路径 可能是这样的C:\someFolder
C:\someFolder\someFile
C:\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/