.NET 경로가 디렉토리가 아닌 파일인지 확인하는 방법은 무엇입니까?
경로가 있고 디렉터리인지 파일인지 확인해야합니다.
경로가 파일인지 확인하는 가장 좋은 방법입니까?
string file = @"C:\Test\foo.txt";
bool isFile = !System.IO.Directory.Exists(file) &&
System.IO.File.Exists(file);
디렉토리의 경우 논리를 뒤집습니다.
string directory = @"C:\Test";
bool isDirectory = System.IO.Directory.Exists(directory) &&
!System.IO.File.Exists(directory);
둘 다 존재하지 않으면 두 가지 모두 가지 않을 것입니다. 따라서 둘 다 존재한다고 가정하십시오.
사용하다:
System.IO.File.GetAttributes(string path)
반환 된 FileAttributes결과에 값이 포함되어 있는지 확인합니다 FileAttributes.Directory.
bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
== FileAttributes.Directory;
두 가지 확인 만 필요한 가장 간단한 방법이라고 생각합니다.
string file = @"C:\tmp";
if (System.IO.Directory.Exists(file))
{
// do stuff when file is an existing directory
}
else if (System.IO.File.Exists(file))
{
// do stuff when file is an existing file
}
몇 가지 interop 코드로이를 수행 할 수 있습니다.
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool PathIsDirectory([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);
일부 의견을 더 명확히하기 위해 ...
비 관리 코드를 도입하는 것은 .NET의 다른 파일 또는 I / O 관련 호출보다 더 이상 본질적으로 위험하지 않습니다.
이것은 문자열을 사용하는 단일 함수 호출입니다. 이 함수를 호출하여 새로운 데이터 유형 및 / 또는 메모리 사용량을 도입하지 않습니다. 예, 제대로 정리하려면 관리되지 않는 코드에 의존해야하지만 궁극적으로 대부분의 I / O 관련 호출에 대한 종속성이 있습니다.
참고로 다음은 Reflector의 File.GetAttributes (string path)에 대한 코드입니다.
public static FileAttributes GetAttributes(string path)
{
string fullPathInternal = Path.GetFullPathInternal(path);
new FileIOPermission(FileIOPermissionAccess.Read, new string[] { fullPathInternal }, false, false).Demand();
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int errorCode = FillAttributeInfo(fullPathInternal, ref data, false, true);
if (errorCode != 0)
{
__Error.WinIOError(errorCode, fullPathInternal);
}
return (FileAttributes) data.fileAttributes;
}
As you can see, it is also calling in to unmanaged code in order to retrieve the file attributes, so the arguements about introducing unmanaged code being dangerous are invalid. Likewise, the argument about staying completely in managed code. There is no managed code implementation to do this. Even calling File.GetAttributes() as the other answers propose have the same "issues" of calling unmanged code and I believe this is the more reliable method to accomplish determining if a path is a directory.
Edit To answer the comment by @Christian K about CAS. I believe the only reason GetAttributes makes the security demand is because it needs to read the properties of the file so it wants to make sure the calling code has permission to do so. This is not the same as the underlying OS checks (if there are any). You can always create a wrapper function around the P/Invoke call to PathIsDirectory that also demands certain CAS permissions, if necessary.
Assuming the directory exists...
bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
== FileAttributes.Directory;
Check this out:
/// <summary>
/// Returns true if the given file path is a folder.
/// </summary>
/// <param name="Path">File path</param>
/// <returns>True if a folder</returns>
public bool IsFolder(string path)
{
return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}
from http://www.jonasjohn.de/snippets/csharp/is-folder.htm
Read the file attributes:
FileAttributes att = System.IO.File.GetAttributes(PATH_TO_FILE);
Check for the Directory flag.
Given that a particular path string cannot represent both a directory and a file, then the following works just fine and opens the door for other operations.
bool isFile = new FileInfo(path).Exists;
bool isDir = new DirectoryInfo(path).Exists;
If you're working with the file system, using FileInfo and DirectoryInfo is much simpler than using strings.
Hmm, it looks like the Files class (in java.nio) actually has a static isDirectory method. So, I think you could actually use the following:
Path what = ...
boolean isDir = Files.isDirectory(what);
참고URL : https://stackoverflow.com/questions/439447/net-how-to-check-if-path-is-a-file-and-not-a-directory
'IT TIP' 카테고리의 다른 글
| int 배열에서 요소의 인덱스를 찾는 방법은 무엇입니까? (0) | 2020.10.25 |
|---|---|
| cat의 출력을 cURL로 파이프하여 파일 목록을 다운로드합니다. (0) | 2020.10.25 |
| 위도와 경도에 대한 올바른 데이터 유형? (0) | 2020.10.25 |
| 안드로이드 보류중인 의도 알림 문제 (0) | 2020.10.25 |
| 프로그래밍 방식으로 ProgressBar를 만드는 방법은 무엇입니까? (0) | 2020.10.25 |