C# :
如果路径是目录或文件,则只能使用此行:C# :,c#,.net,file,path,directory,C#,.net,File,Path,Directory,如果路径是目录或文件,则只能使用此行: File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory) 这是我的: bool IsPathDirectory(string path) { if (path == null) throw new ArgumentNullException("path"); path = path.Trim(); if (Directo
File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory)
这是我的:
bool IsPathDirectory(string path)
{
if (path == null) throw new ArgumentNullException("path");
path = path.Trim();
if (Directory.Exists(path))
return true;
if (File.Exists(path))
return false;
// neither file nor directory exists. guess intention
// if has trailing slash then it's a directory
if (new[] {"\\", "/"}.Any(x => path.EndsWith(x)))
return true; // ends with slash
// if has extension then its a file; directory otherwise
return string.IsNullOrWhiteSpace(Path.GetExtension(path));
}
这与其他人的答案相似,但并不完全相同。我知道游戏进行得太晚了,但我想我还是要分享一下。如果您仅将路径作为字符串使用,则很容易找到答案:
using System;
using System.IO;
namespace FileOrDirectory
{
class Program
{
public static string FileOrDirectory(string path)
{
if (File.Exists(path))
return "File";
if (Directory.Exists(path))
return "Directory";
return "Path Not Exists";
}
static void Main()
{
Console.WriteLine("Enter The Path:");
string path = Console.ReadLine();
Console.WriteLine(FileOrDirectory(path));
}
}
}
private bool IsFolder(string ThePath)
{
string BS = Path.DirectorySeparatorChar.ToString();
return Path.GetDirectoryName(ThePath) == ThePath.TrimEnd(BS.ToCharArray());
}
例如:
路径==“C:\SomeFolder\File1.txt”
将以以下方式结束:
return "C:\SomeFolder" == "C:\SomeFolder\File1.txt" (FALSE)
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
另一个例子:
路径==“C:\SomeFolder\”
最终将是:
return "C:\SomeFolder" == "C:\SomeFolder\File1.txt" (FALSE)
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
这也可以在没有尾随反斜杠的情况下工作:
路径==“C:\SomeFolder”
最终将是:
return "C:\SomeFolder" == "C:\SomeFolder\File1.txt" (FALSE)
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
请记住,这只适用于路径本身,而不适用于路径与“物理磁盘”之间的关系。。。因此,它不能告诉你路径/文件是否存在或类似的东西,但它肯定能告诉你路径是文件夹还是文件…我需要这个,帖子帮助,这会让它下降到一行,如果路径根本不是路径,它只会返回并退出该方法。它解决了上述所有问题,也不需要后面的斜杠
if (!Directory.Exists(@"C:\folderName")) return;
使用这篇文章中选择的答案,我查看了评论,并相信 @ŞafakGür、@Anthony和@Quinn Wilson,感谢他们的信息,这些信息引导我找到了我编写和测试的改进答案:
/// <summary>
/// Returns true if the path is a dir, false if it's a file and null if it's neither or doesn't exist.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool? IsDirFile(this string path)
{
bool? result = null;
if(Directory.Exists(path) || File.Exists(path))
{
// get the file attributes for file or directory
var fileAttr = File.GetAttributes(path);
if (fileAttr.HasFlag(FileAttributes.Directory))
result = true;
else
result = false;
}
return result;
}
//
///如果路径是dir,则返回true;如果路径是文件,则返回false;如果路径不存在或不存在,则返回null。
///
///
///
公共静态布尔?IsDirFile(此字符串路径)
{
bool?结果=null;
if(Directory.Exists(path)| | File.Exists(path))
{
//获取文件或目录的文件属性
var fileAttr=File.GetAttributes(路径);
if(fileAttr.HasFlag(FileAttributes.Directory))
结果=真;
其他的
结果=假;
}
返回结果;
}
这不管用吗
var isFile = Regex.IsMatch(path, @"\w{1,}\.\w{1,}$");
在综合了其他答案的建议后,我意识到我的想法和你的差不多。以下是一些测试,指出一些需要思考的问题:
C:\Temp\folder\u with.dot
Path.directoryseportorchar
和Path.altdirectoryseportorchar
)//
///是否为文件夹(是否存在);
///或者假设它“看起来”不像一个文件,那么它就是一个目录。
///
///检查路径
///如果不存在,它至少看起来像一个目录名吗?在中,它看起来不像一个文件。
///如果是文件夹/目录,则为True;如果不是,则为false。
公共静态bool-IsFolder(字符串路径,bool-assumeDneLookAlike=true)
{
// https://stackoverflow.com/questions/1395205/better-way-to-check-if-path-is-a-file-or-a-directory
//结果证明与https://stackoverflow.com/a/19596821/1037948
//按真实性顺序检查
//存在或以目录分隔符结尾--文件不能以目录分隔符结尾,对吗?
if(目录.Exists)(路径)
//使用系统值,而不是采用斜杠
||path.EndsWith(“+path.DirectorySeparatorChar)
||path.EndsWith(“+path.altdirectoryseportorchar))
返回true;
//如果我们确定这是一个真实的文件。。。
if(File.Exists(path))
返回false;
//如果它有扩展名,它应该是一个文件,反之亦然
//虽然技术上目录可以有扩展。。。
if(!Path.HasExtension(Path)&&assumedNelooklike)
返回true;
//仅适用于现有文件,与上面的“.Exists”有点多余
//if(File.GetAttributes(path).HasFlag(FileAttributes.Directory))。。。;
//不知道--可能返回“不确定”值(可为null的bool)
//或者假设如果我们不知道,那么它不是一个文件夹
返回false;
}
可能用于UWP C#
公共静态异步任务AsIStorageItemAsync(此字符串为iStorageItemPath)
{
if(string.IsNullOrEmpty(iStorageItemPath))返回null;
IStorageItem-storageItem=null;
尝试
{
storageItem=等待StorageFolder.GetFolderFromPathAsync(iStorageItemPath);
如果(storageItem!=null)返回storageItem;
}捕获{}
尝试
{
storageItem=等待StorageFile.GetFileFromPathAsync(iStorageItemPath);
如果(storageItem!=null)返回storageItem;
}捕获{}
退货项目;
}
我明白了,我参加聚会已经晚了10年。
我面临的情况是,从某些属性中,我可以接收文件名或完整的文件路径。如果没有提供路径,我必须通过附加另一个属性提供的“全局”目录路径来检查文件是否存在
就我而言
var isFileName = System.IO.Path.GetFileName (str) == str;
成功了。
好吧,这不是魔术,但也许这可以节省一些人几分钟的时间。
因为这只是一个字符串解析,所以带点的目录名可能会给出误报 很晚才来到这里,但我发现
null
返回值非常难看-IsDirectory(字符串路径)
returningnull
并不等同于没有详细注释的不存在的路径,因此我提出了以下建议:
public static class PathHelper
{
/// <summary>
/// Determines whether the given path refers to an existing file or directory on disk.
/// </summary>
/// <param name="path">The path to test.</param>
/// <param name="isDirectory">When this method returns, contains true if the path was found to be an existing directory, false in all other scenarios.</param>
/// <returns>true if the path exists; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException">If <paramref name="path"/> equals <see cref="string.Empty"/></exception>
public static bool PathExists(string path, out bool isDirectory)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (path == string.Empty) throw new ArgumentException("Value cannot be empty.", nameof(path));
isDirectory = Directory.Exists(path);
return isDirectory || File.Exists(path);
}
}
公共静态类PathHelper
{
///
///确定给定路径是否引用磁盘上的现有文件或目录。
///
///测试的路径。
///当此方法返回时,如果发现路径是现有目录,则包含true,在所有其他情况下包含false。
///如果路径存在,则为true;否则为false。
///If为空。
///如果相等
公共静态bool路径存在(字符串路径,out bool isDirectory)
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
if (!Directory.Exists(@"C:\folderName")) return;
/// <summary>
/// Returns true if the path is a dir, false if it's a file and null if it's neither or doesn't exist.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool? IsDirFile(this string path)
{
bool? result = null;
if(Directory.Exists(path) || File.Exists(path))
{
// get the file attributes for file or directory
var fileAttr = File.GetAttributes(path);
if (fileAttr.HasFlag(FileAttributes.Directory))
result = true;
else
result = false;
}
return result;
}
var isFile = Regex.IsMatch(path, @"\w{1,}\.\w{1,}$");
var paths = new[] {
// exists
@"C:\Temp\dir_test\folder_is_a_dir",
@"C:\Temp\dir_test\is_a_dir_trailing_slash\",
@"C:\Temp\dir_test\existing_folder_with.ext",
@"C:\Temp\dir_test\file_thats_not_a_dir",
@"C:\Temp\dir_test\notadir.txt",
// doesn't exist
@"C:\Temp\dir_test\dne_folder_is_a_dir",
@"C:\Temp\dir_test\dne_folder_trailing_slash\",
@"C:\Temp\dir_test\non_existing_folder_with.ext",
@"C:\Temp\dir_test\dne_file_thats_not_a_dir",
@"C:\Temp\dir_test\dne_notadir.txt",
};
foreach(var path in paths) {
IsFolder(path/*, false*/).Dump(path);
}
C:\Temp\dir_test\folder_is_a_dir
True
C:\Temp\dir_test\is_a_dir_trailing_slash\
True
C:\Temp\dir_test\existing_folder_with.ext
True
C:\Temp\dir_test\file_thats_not_a_dir
False
C:\Temp\dir_test\notadir.txt
False
C:\Temp\dir_test\dne_folder_is_a_dir
True
C:\Temp\dir_test\dne_folder_trailing_slash\
True
C:\Temp\dir_test\non_existing_folder_with.ext
False (this is the weird one)
C:\Temp\dir_test\dne_file_thats_not_a_dir
True
C:\Temp\dir_test\dne_notadir.txt
False
/// <summary>
/// Whether the <paramref name="path"/> is a folder (existing or not);
/// optionally assume that if it doesn't "look like" a file then it's a directory.
/// </summary>
/// <param name="path">Path to check</param>
/// <param name="assumeDneLookAlike">If the <paramref name="path"/> doesn't exist, does it at least look like a directory name? As in, it doesn't look like a file.</param>
/// <returns><c>True</c> if a folder/directory, <c>false</c> if not.</returns>
public static bool IsFolder(string path, bool assumeDneLookAlike = true)
{
// https://stackoverflow.com/questions/1395205/better-way-to-check-if-path-is-a-file-or-a-directory
// turns out to be about the same as https://stackoverflow.com/a/19596821/1037948
// check in order of verisimilitude
// exists or ends with a directory separator -- files cannot end with directory separator, right?
if (Directory.Exists(path)
// use system values rather than assume slashes
|| path.EndsWith("" + Path.DirectorySeparatorChar)
|| path.EndsWith("" + Path.AltDirectorySeparatorChar))
return true;
// if we know for sure that it's an actual file...
if (File.Exists(path))
return false;
// if it has an extension it should be a file, so vice versa
// although technically directories can have extensions...
if (!Path.HasExtension(path) && assumeDneLookAlike)
return true;
// only works for existing files, kinda redundant with `.Exists` above
//if( File.GetAttributes(path).HasFlag(FileAttributes.Directory) ) ...;
// no idea -- could return an 'indeterminate' value (nullable bool)
// or assume that if we don't know then it's not a folder
return false;
}
public static async Task<IStorageItem> AsIStorageItemAsync(this string iStorageItemPath)
{
if (string.IsNullOrEmpty(iStorageItemPath)) return null;
IStorageItem storageItem = null;
try
{
storageItem = await StorageFolder.GetFolderFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
try
{
storageItem = await StorageFile.GetFileFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
return storageItem;
}
var isFileName = System.IO.Path.GetFileName (str) == str;
public static class PathHelper
{
/// <summary>
/// Determines whether the given path refers to an existing file or directory on disk.
/// </summary>
/// <param name="path">The path to test.</param>
/// <param name="isDirectory">When this method returns, contains true if the path was found to be an existing directory, false in all other scenarios.</param>
/// <returns>true if the path exists; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException">If <paramref name="path"/> equals <see cref="string.Empty"/></exception>
public static bool PathExists(string path, out bool isDirectory)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (path == string.Empty) throw new ArgumentException("Value cannot be empty.", nameof(path));
isDirectory = Directory.Exists(path);
return isDirectory || File.Exists(path);
}
}
/// <summary>
/// Example usage of <see cref="PathExists(string, out bool)"/>
/// </summary>
public static void Usage()
{
const string path = @"C:\dev";
if (!PathHelper.PathExists(path, out var isDirectory))
return;
if (isDirectory)
{
// Do something with your directory
}
else
{
// Do something with your file
}
}
public static class Utility
{
public enum ePathType
{
ePathType_Unknown = 0,
ePathType_ExistingFile = 1,
ePathType_ExistingFolder = 2,
ePathType_ExistingFolder_FolderSelectionAdded = 3,
}
public static ePathType GetPathType(string path)
{
if (File.Exists(path) == true) { return ePathType.ePathType_ExistingFile; }
if (Directory.Exists(path) == true) { return ePathType.ePathType_ExistingFolder; }
if (path.EndsWith("Folder Selection.") == true)
{
// Test the path again without "Folder Selection."
path = path.Replace("\\Folder Selection.", "");
if (Directory.Exists(path) == true)
{
// Could return ePathType_ExistingFolder, but prefer to let the caller known their path has text to remove...
return ePathType.ePathType_ExistingFolder_FolderSelectionAdded;
}
}
return ePathType.ePathType_Unknown;
}
}
`public bool IsDirectory( string path ) {
return string.IsNullOrEmpty( Path.GetFileName( path ) ) || Directory.Exists( path );
}`