programing

경로가 파일인지 디렉토리인지 확인하는 더 좋은 방법은 무엇입니까?

elecom 2023. 5. 8. 21:52
반응형

경로가 파일인지 디렉토리인지 확인하는 더 좋은 방법은 무엇입니까?

는 a의 하고 있습니다.TreeView디렉터리 및 파일의.사용자는 파일 또는 디렉토리를 선택한 후 이를 사용하여 작업을 수행할 수 있습니다.이를 위해서는 사용자의 선택에 따라 다른 작업을 수행하는 방법이 필요합니다.

현재 경로가 파일인지 디렉토리인지 확인하기 위해 다음과 같은 작업을 수행하고 있습니다.

bool bIsFile = false;
bool bIsDirectory = false;

try
{
    string[] subfolders = Directory.GetDirectories(strFilePath);

    bIsDirectory = true;
    bIsFile = false;
}
catch(System.IO.IOException)
{
    bIsFolder = false;
    bIsFile = true;
}

저는 이것을 하는 더 좋은 방법이 있다는 것을 느끼지 않을 수 없습니다!저는 기준을 찾고 싶었습니다.이것을 처리할 수 있는 NET 방법이지만, 저는 그렇게 할 수 없었습니다.이러한 방법이 존재합니까? 만약 존재하지 않는다면 경로가 파일인지 디렉토리인지를 결정하는 가장 간단한 방법은 무엇입니까?

경로가 파일인지 디렉토리인지 확인하는 방법:

// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:\Temp");

//detect whether its a directory or file
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
    MessageBox.Show("Its a directory");
else
    MessageBox.Show("Its a file");

에 대한 업데이트.NET 4.0+

아래 설명에 따라 설정합니다.NET 4.0 이상(최대 성능은 중요하지 않음) 코드를 더 깨끗하게 작성할 수 있습니다.

// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:\Temp");

if (attr.HasFlag(FileAttributes.Directory))
    MessageBox.Show("Its a directory");
else
    MessageBox.Show("Its a file");

이것을 사용하는 것은 어떻습니까?

if(File.Exists(data.path))
{
    // is file
}
else if(Directory.Exists(data.path))
{
   // is Folder 
}
else
{
   // invalid path
}

File.Exists()는 디렉터리가 존재하더라도 파일이 아닌 경우 false를 반환하므로 true를 반환하면 파일이 있다는 것을 알고 있고, false를 반환하면 디렉터리 또는 잘못된 경로가 있으므로 다음으로 디렉터리가 있는 유효한 디렉터리인지 테스트합니다.exists()가 true를 반환하면 잘못된 경로인 디렉터리가 있습니다.

경로가 디렉토리 또는 파일인 경우 이 행만 사용하여 얻을 수 있습니다.

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));
    }

그것은 다른 사람들의 대답과 비슷하지만 정확히 같지는 않습니다.

다른 답변들의 제안들을 종합해 본 후, 저는 제가 로니 오버비의 답변과 거의 같은 것을 생각해 냈다는 것을 깨달았습니다.다음은 고려해야 할 몇 가지 사항을 지적하기 위한 몇 가지 테스트입니다.

  1. 가 있을 수 .C:\Temp\folder_with.dot
  2. 파일이 디렉토리 구분자로 끝날 수 없음(아래 참조)
  3. 기술적으로 플랫폼에 특정한 두 개의 디렉토리 구분자가 있습니다. 즉, 슬래시일 도 있고 아닐 도 있습니다.Path.DirectorySeparatorChar그리고.Path.AltDirectorySeparatorChar)

검정(Linqpad)

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;
}

디렉토리의 대안으로 사용합니다.존재합니다(). 파일을 사용할 수 있습니다.GetAttributes() 메서드를 사용하여 다음과 같은 도우미 메서드를 만들 수 있습니다.

private static bool IsDirectory(string path)
{
    System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
    return (fa & FileAttributes.Directory) != 0;
}

항목에 대한 추가 메타데이터가 포함된 컨트롤을 채울 때 TreeView 컨트롤의 태그 속성에 개체를 추가할 수도 있습니다.예를 들어 파일 및 디렉터리에 대한 FileInfo 개체를 추가할 수 있습니다.항목을 클릭할 때 해당 데이터를 얻기 위해 추가 시스템 호출을 수행하는 것을 저장하기 위해 태그 속성에서 항목 유형을 테스트합니다.

Exists(존재) 및 Attributes(속성) 속성의 동작을 고려할 때 이 방법이 최선이었습니다.

using System.IO;

public static class FileSystemInfoExtensions
{
    /// <summary>
    /// Checks whether a FileInfo or DirectoryInfo object is a directory, or intended to be a directory.
    /// </summary>
    /// <param name="fileSystemInfo"></param>
    /// <returns></returns>
    public static bool IsDirectory(this FileSystemInfo fileSystemInfo)
    {
        if (fileSystemInfo == null)
        {
            return false;
        }

        if ((int)fileSystemInfo.Attributes != -1)
        {
            // if attributes are initialized check the directory flag
            return fileSystemInfo.Attributes.HasFlag(FileAttributes.Directory);
        }

        // If we get here the file probably doesn't exist yet.  The best we can do is 
        // try to judge intent.  Because directories can have extensions and files
        // can lack them, we can't rely on filename.
        // 
        // We can reasonably assume that if the path doesn't exist yet and 
        // FileSystemInfo is a DirectoryInfo, a directory is intended.  FileInfo can 
        // make a directory, but it would be a bizarre code path.

        return fileSystemInfo is DirectoryInfo;
    }
}

테스트 방법은 다음과 같습니다.

    [TestMethod]
    public void IsDirectoryTest()
    {
        // non-existing file, FileAttributes not conclusive, rely on type of FileSystemInfo
        const string nonExistentFile = @"C:\TotallyFakeFile.exe";

        var nonExistentFileDirectoryInfo = new DirectoryInfo(nonExistentFile);
        Assert.IsTrue(nonExistentFileDirectoryInfo.IsDirectory());

        var nonExistentFileFileInfo = new FileInfo(nonExistentFile);
        Assert.IsFalse(nonExistentFileFileInfo.IsDirectory());

        // non-existing directory, FileAttributes not conclusive, rely on type of FileSystemInfo
        const string nonExistentDirectory = @"C:\FakeDirectory";

        var nonExistentDirectoryInfo = new DirectoryInfo(nonExistentDirectory);
        Assert.IsTrue(nonExistentDirectoryInfo.IsDirectory());

        var nonExistentFileInfo = new FileInfo(nonExistentDirectory);
        Assert.IsFalse(nonExistentFileInfo.IsDirectory());

        // Existing, rely on FileAttributes
        const string existingDirectory = @"C:\Windows";

        var existingDirectoryInfo = new DirectoryInfo(existingDirectory);
        Assert.IsTrue(existingDirectoryInfo.IsDirectory());

        var existingDirectoryFileInfo = new FileInfo(existingDirectory);
        Assert.IsTrue(existingDirectoryFileInfo.IsDirectory());

        // Existing, rely on FileAttributes
        const string existingFile = @"C:\Windows\notepad.exe";

        var existingFileDirectoryInfo = new DirectoryInfo(existingFile);
        Assert.IsFalse(existingFileDirectoryInfo.IsDirectory());

        var existingFileFileInfo = new FileInfo(existingFile);
        Assert.IsFalse(existingFileFileInfo.IsDirectory());
    }
public bool IsDirectory(string path) {
    return string.IsNullOrEmpty(Path.GetFileName(path)) || Directory.Exists(path);
}

경로 파일 이름이 빈 문자열인지 또는 디렉터리가 있는지 확인합니다.이렇게 하면 기존 오류에 대한 중복성을 제공하는 동안 파일 특성 오류가 발생하지 않습니다.

다음과 같은 기능을 사용합니다.

using System;

using System.IO;

namespace crmachine.CommonClasses
{

  public static class CRMPath
  {

    public static bool IsDirectory(string path)
    {
      if (path == null)
      {
        throw new ArgumentNullException("path");
      }

      string reason;
      if (!IsValidPathString(path, out reason))
      {
        throw new ArgumentException(reason);
      }

      if (!(Directory.Exists(path) || File.Exists(path)))
      {
        throw new InvalidOperationException(string.Format("Could not find a part of the path '{0}'",path));
      }

      return (new System.IO.FileInfo(path).Attributes & FileAttributes.Directory) == FileAttributes.Directory;
    } 

    public static bool IsValidPathString(string pathStringToTest, out string reasonForError)
    {
      reasonForError = "";
      if (string.IsNullOrWhiteSpace(pathStringToTest))
      {
        reasonForError = "Path is Null or Whitespace.";
        return false;
      }
      if (pathStringToTest.Length > CRMConst.MAXPATH) // MAXPATH == 260
      {
        reasonForError = "Length of path exceeds MAXPATH.";
        return false;
      }
      if (PathContainsInvalidCharacters(pathStringToTest))
      {
        reasonForError = "Path contains invalid path characters.";
        return false;
      }
      if (pathStringToTest == ":")
      {
        reasonForError = "Path consists of only a volume designator.";
        return false;
      }
      if (pathStringToTest[0] == ':')
      {
        reasonForError = "Path begins with a volume designator.";
        return false;
      }

      if (pathStringToTest.Contains(":") && pathStringToTest.IndexOf(':') != 1)
      {
        reasonForError = "Path contains a volume designator that is not part of a drive label.";
        return false;
      }
      return true;
    }

    public static bool PathContainsInvalidCharacters(string path)
    {
      if (path == null)
      {
        throw new ArgumentNullException("path");
      }

      bool containedInvalidCharacters = false;

      for (int i = 0; i < path.Length; i++)
      {
        int n = path[i];
        if (
            (n == 0x22) || // "
            (n == 0x3c) || // <
            (n == 0x3e) || // >
            (n == 0x7c) || // |
            (n  < 0x20)    // the control characters
          )
        {
          containedInvalidCharacters = true;
        }
      }

      return containedInvalidCharacters;
    }


    public static bool FilenameContainsInvalidCharacters(string filename)
    {
      if (filename == null)
      {
        throw new ArgumentNullException("filename");
      }

      bool containedInvalidCharacters = false;

      for (int i = 0; i < filename.Length; i++)
      {
        int n = filename[i];
        if (
            (n == 0x22) || // "
            (n == 0x3c) || // <
            (n == 0x3e) || // >
            (n == 0x7c) || // |
            (n == 0x3a) || // : 
            (n == 0x2a) || // * 
            (n == 0x3f) || // ? 
            (n == 0x5c) || // \ 
            (n == 0x2f) || // /
            (n  < 0x20)    // the control characters
          )
        {
          containedInvalidCharacters = true;
        }
      }

      return containedInvalidCharacters;
    }

  }

}

가장 정확한 방법은 shlwapi의 interop 코드를 사용하는 것입니다.dll

[DllImport(SHLWAPI, CharSet = CharSet.Unicode)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool PathIsDirectory([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);

그러면 다음과 같이 부를 수 있습니다.

#region IsDirectory
/// <summary>
/// Verifies that a path is a valid directory.
/// </summary>
/// <param name="path">The path to verify.</param>
/// <returns><see langword="true"/> if the path is a valid directory; 
/// otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <para><paramref name="path"/> is <see langword="null"/>.</para>
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <para><paramref name="path"/> is <see cref="F:System.String.Empty">String.Empty</see>.</para>
/// </exception>
public static bool IsDirectory(string path)
{
    return PathIsDirectory(path);
}

파일 또는 폴더가 실제로 존재하지 않을 수 있는 경우 파일 또는 폴더에 대한 경로를 확인해야 한다는 점을 제외하고는 유사한 문제가 발생했을 때 이 문제를 발견했습니다.위의 답변에 대해 이 시나리오에서는 작동하지 않을 것이라고 언급한 의견이 몇 개 있었습니다.해결책을 찾았습니다(VB 사용).NET, 하지만 필요하면 변환 가능), 저에게 잘 맞는 것 같습니다.

Dim path As String = "myFakeFolder\ThisDoesNotExist\"
Dim bIsFolder As Boolean = (IO.Path.GetExtension(path) = "")
'returns True

Dim path As String = "myFakeFolder\ThisDoesNotExist\File.jpg"
Dim bIsFolder As Boolean = (IO.Path.GetExtension(path) = "")
'returns False

이것이 누군가에게 도움이 되기를 바랍니다!

경로만을 문자열로 사용하는 경우 이 문제를 쉽게 파악할 수 있습니다.

private bool IsFolder(string ThePath)
{
    string BS = Path.DirectorySeparatorChar.ToString();
    return Path.GetDirectoryName(ThePath) == ThePath.TrimEnd(BS.ToCharArray());
}

예:ThePath == "C:\SomeFolder\File1.txt"결국 이렇게 될 것입니다.

return "C:\SomeFolder" == "C:\SomeFolder\File1.txt" // FALSE

예: 다른예:ThePath == "C:\SomeFolder\"결국 이렇게 될 것입니다.

return "C:\SomeFolder" == "C:\SomeFolder" // TRUE

백슬래시 할 수 : 후백없작동합니다이도시슬래이행는▁and다작니.ThePath == "C:\SomeFolder"결국 이렇게 될 것입니다.

return "C:\SomeFolder" == "C:\SomeFolder" // TRUE

이 기능은 경로 자체에서만 작동하고 경로와 실제 디스크 간의 관계에서는 작동하지 않으므로 경로/파일이 존재하는지 여부는 알 수 없지만 경로가 폴더인지 파일인지는 알 수 있습니다.

"숨김" 및 "시스템"으로 표시된 디렉토리를 포함하여 디렉토리를 찾으려면 이 작업을 수행합니다(필수).NET V4):

FileAttributes fa = File.GetAttributes(path);
if(fa.HasFlag(FileAttributes.Directory)) 

저는 이것이 필요했고, 게시물은 도움을 주었고, 이것은 그것을 한 줄로 요약했습니다. 만약 그 경로가 전혀 경로가 아니라면, 그것은 그냥 되돌아와서 메소드를 종료합니다.위의 모든 문제를 해결하며 후행 슬래시도 필요하지 않습니다.

if (!Directory.Exists(@"C:\folderName")) return;

그렇군요, 파티에 10년이나 늦었네요.어떤 속성에서 파일 이름 또는 전체 파일 경로를 수신할 수 있는 상황에 직면했습니다.경로가 제공되지 않으면 다른 속성에서 제공한 "글로벌" 디렉터리 경로를 첨부하여 파일 존재 여부를 확인해야 합니다.

내 경우에는

var isFileName = System.IO.Path.GetFileName (str) == str;

속임수를 썼습니다.좋아요, 마법은 아니지만, 아마도 이것은 누군가가 이해하는 데 몇 분을 절약할 수 있을 것입니다.이것은 문자열 구문 분석일 뿐이므로 점이 있는 Dir-names는 잘못된 긍정을 줄 수 있습니다...

다음을 사용합니다. 확장자도 테스트합니다. 즉, 제공된 경로가 파일이지만 존재하지 않는 파일인지 테스트하는 데 사용할 수 있습니다.

private static bool isDirectory(string path)
{
    bool result = true;
    System.IO.FileInfo fileTest = new System.IO.FileInfo(path);
    if (fileTest.Exists == true)
    {
        result = false;
    }
    else
    {
        if (fileTest.Extension != "")
        {
            result = false;
        }
    }
    return result;
}
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));
          }
     }
}

이 게시물의 선택된 답변을 사용하여, 저는 댓글을 보고 제가 작성하고 테스트한 이 개선된 답변을 이끌어 준 @ShafakGü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;
    }

아마도 UWPC#일 것입니다.

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;
    }

여기 파티에 매우 늦었지만 저는 그것을 찾았습니다.Nullable<Boolean>값을 꽤 추하게 반환합니다.IsDirectory(string path)돌아오는null자세한 설명 없이는 존재하지 않는 경로와 동일하지 않으므로 다음과 같은 방법을 생각해 냈습니다.

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
    }
}

경로에 프린지 대소문자 추가 중 - "폴더 선택" 선택

앱에서 최근에 열린 경로가 제게 전달되고, 그 중 일부는 끝에 "폴더 선택"이 있습니다.

일부 FileOpenDialogs 및 WinMerge는 경로에 "폴더 선택"을 추가합니다(참).

경로에 추가되는 "폴더 선택"을 표시하는 대화상자

그러나 Windows OS에서 "폴더 선택"은 권장되는 파일 또는 폴더 이름이 아닙니다(예: 하지 않음, 절대로 흔들지 않음).여기에 언급된 바와 같이: http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx

파일 또는 디렉토리 이름을 공백 또는 마침표로 끝내지 마십시오.기본 파일 시스템이 이러한 이름을 지원할 수 있지만 윈도우즈 셸 및 사용자 인터페이스는 지원하지 않습니다.그러나 이름의 첫 번째 문자로 마침표를 지정할 수 있습니다.예를 들어 ".temp"입니다.

그래서 "폴더 선택"을 사용해서는 안 되지만, 사용할 수 있습니다. (훌륭합니다.)

충분한 설명 - 내 코드(나는 열거형을 많이 좋아합니다):

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 static bool IsFolder(string path)
{
    if (string.IsNullOrEmpty(path)) return false;
    if (path.EndsWith("\\")) return true;
    return (path.Contains("\\") && string.IsNullOrEmpty(Path.GetExtension(path)));
}

안 될까요?

var isFile = Regex.IsMatch(path, @"\w{1,}\.\w{1,}$");

언급URL : https://stackoverflow.com/questions/1395205/better-way-to-check-if-a-path-is-a-file-or-a-directory

반응형