경로에서 폴더 이름 얻기
string path = "C:/folder1/folder2/file.txt";
어떤 객체 또는 메소드를 사용하여 결과를 얻을 수 folder2
있습니까?
아마 다음과 같은 것을 사용할 것입니다 :
string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );
내부 호출 GetDirectoryName
은 전체 경로를 반환하고 외부 호출 GetFileName()
은 마지막 경로 구성 요소 (폴더 이름)를 반환합니다.
이 방법은 경로가 실제로 존재하는지 여부에 관계없이 작동합니다. 그러나이 방법은 파일 이름으로 처음 끝나는 경로에 의존합니다. 경로가 파일 이름 또는 폴더 이름으로 끝나는 지 여부를 알 수없는 경우 실제 경로를 확인하여 파일 / 폴더가 먼저 위치에 있는지 확인해야합니다. 이 경우 Dan Dimitru의 답변이 더 적합 할 수 있습니다.
이 시도:
string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;
간단하고 깨끗합니다. 만 사용 System.IO.FileSystem
-매력처럼 작동합니다.
string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;
DirectoryInfo 는 디렉토리 이름을 제거하는 작업을 수행합니다.
string my_path = @"C:\Windows\System32";
DirectoryInfo dir_info = new DirectoryInfo(my_path);
string directory = dir_info.Name; // System32
파일 이름이 경로에 없을 때이 코드 스 니펫을 사용하여 경로의 디렉토리를 가져옵니다.
예를 들어 "c : \ tmp \ test \ visual";
string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));
산출:
시각적
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
아래 코드는 폴더 이름 만 얻는 데 도움이됩니다.
공개 ObservableCollection 항목 = 새로운 ObservableCollection (); 시험 { 문자열 [] folderPaths = Directory.GetDirectories (stemp); items.Clear (); foreach (폴더 경로의 문자열 s) { items.Add (new gridItems {foldername = s.Remove (0, s.LastIndexOf ( '\\') + 1), folderpath = s}); } } 캐치 (예외 a) { } 공개 클래스 gridItems { 공개 문자열 폴더 이름 {get; 세트; } 공개 문자열 폴더 경로 {get; 세트; } }
이것은 추악하지만 할당을 피합니다.
private static string GetFolderName(string path)
{
var end = -1;
for (var i = path.Length; --i >= 0;)
{
var ch = path[i];
if (ch == System.IO.Path.DirectorySeparatorChar ||
ch == System.IO.Path.AltDirectorySeparatorChar ||
ch == System.IO.Path.VolumeSeparatorChar)
{
if (end > 0)
{
return path.Substring(i + 1, end - i - 1);
}
end = i;
}
}
if (end > 0)
{
return path.Substring(0, end);
}
return path;
}
또한 루프에서 디렉토리 이름 목록을 가져 오는 동안 DirectoryInfo
클래스가 한 번 초기화되므로 처음 호출 만 허용됩니다. 이 제한을 무시하려면 루프 내에서 변수를 사용하여 개별 디렉토리 이름을 저장하십시오.
예를 들어,이 샘플 코드는 부모 디렉토리 내의 디렉토리 목록을 반복하면서 찾은 각 디렉토리 이름을 문자열 유형 목록에 추가합니다.
[씨#]
string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();
foreach (var directory in parentDirectory)
{
// Notice I've created a DirectoryInfo variable.
DirectoryInfo dirInfo = new DirectoryInfo(directory);
// And likewise a name variable for storing the name.
// If this is not added, only the first directory will
// be captured in the loop; the rest won't.
string name = dirInfo.Name;
// Finally we add the directory name to our defined List.
directories.Add(name);
}
[VB.NET]
Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()
For Each directory In parentDirectory
' Notice I've created a DirectoryInfo variable.
Dim dirInfo As New DirectoryInfo(directory)
' And likewise a name variable for storing the name.
' If this is not added, only the first directory will
' be captured in the loop; the rest won't.
Dim name As String = dirInfo.Name
' Finally we add the directory name to our defined List.
directories.Add(name)
Next directory
참고 URL : https://stackoverflow.com/questions/3736462/getting-the-folder-name-from-a-path
'IT' 카테고리의 다른 글
'SubSonic.Schema .DatabaseColumn'유형의 오브젝트를 직렬화하는 중에 순환 참조가 발견되었습니다. (0) | 2020.05.28 |
---|---|
string.isEmpty () 또는“”.equals (string)을 사용해야합니까? (0) | 2020.05.28 |
MySQL-행에서 열로 (0) | 2020.05.28 |
Eclipse에서 자동 정렬 바로 가기 키란 무엇입니까? (0) | 2020.05.28 |
디렉토리에있는 확장자의 모든 파일을 gitignore (0) | 2020.05.28 |