判断路径是否存在文件或文件夹

判断文件夹是否存在

1
2
3
4
5
string path = Application.StartupPath + "\\新建文件夹";
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}

判断文件是否存在

1
2
3
4
5
6
7
8
9
string path = Application.StartupPath + "\\新建文件夹\\test.txt"
if(System.IO.File.Exists(path))
{
Console.WriteLine("存在该文件");
}
else
{
Console.WriteLine("不存在该文件");
}

判断路径为文件或文件夹

方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/// <summary>
/// 判断目标是文件夹还是目录(目录包括磁盘)
/// </summary>
/// <param name="filepath">路径</param>
/// <returns>返回true为一个文件夹,返回false为一个文件</returns>
public static bool IsDir(string filepath)
{
FileInfo fi = new FileInfo(filepath);
if ((fi.Attributes & FileAttributes.Directory) != 0)
{
return true;
}
else
{
return false;
}
}

方法二:

1
2
3
4
5
6
7
8
9
10
11
12
if (File.Exists(add_file))
{
Console.WriteLine("是文件");
}
else if (Directory.Exists(targetPath))
{
Console.WriteLine("是文件夹");
}
else
{
Console.WriteLine("都不是");
}

相关链接(侵删)

  1. C# 判断文件路径或文件是否存在
  2. C# 判断一个路径是文件夹还是文件

=================我是分割线=================

欢迎到公众号来唠嗑: