몇 개의 폴더를 위로 탐색하는 방법은 무엇입니까?
한 가지 옵션은 System.IO.Directory.GetParent ()를 몇 번 수행하는 것입니다. 실행중인 어셈블리가있는 위치에서 몇 개의 폴더를 위로 이동하는보다 우아한 방법이 있습니까?
내가하려는 것은 응용 프로그램 폴더 위의 한 폴더에있는 텍스트 파일을 찾는 것입니다. 그러나 어셈블리 자체는 응용 프로그램 폴더 깊은 곳에있는 몇 개의 폴더 인 저장소 안에 있습니다.
다른 간단한 방법은 다음과 같습니다.
string path = @"C:\Folder1\Folder2\Folder3\Folder4";
string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\"));
참고 이것은 두 단계 위로 올라갑니다. 결과는 다음과 같습니다.newPath = @"C:\Folder1\Folder2\";
c : \ folder1 \ folder2 \ folder3 \ bin이 경로 인 경우 다음 코드는 bin 폴더의 경로 기본 폴더를 반환합니다.
//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());
string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();
즉, c : \ folder1 \ folder2 \ folder3
folder2 경로를 원한다면 다음과 같이 디렉토리를 얻을 수 있습니다.
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
그러면 c : \ folder1 \ folder2 \로 경로가 표시됩니다.
..\path
한 단계 위로 ..\..\path
이동하고 경로에서 두 단계 위로 이동 하는 데 사용할 수 있습니다 .
Path
수업도 사용할 수 있습니다 .
이것이 저에게 가장 잘 맞는 것입니다.
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));
'올바른'경로를 얻는 것은 문제가 아니 었습니다. '../'를 추가하는 것은 당연한 일이지만 그 후에는 주어진 문자열을 사용할 수 없습니다. 왜냐하면 마지막에 '../'만 추가하기 때문입니다. 로 둘러싸면 Path.GetFullPath()
사용 가능한 절대 경로가 제공됩니다.
다음 방법은 응용 프로그램 시작 경로 (* .exe 폴더)로 시작하는 파일을 검색합니다. 파일을 찾을 수없는 경우 파일을 찾거나 루트 폴더에 도달 할 때까지 상위 폴더가 검색됩니다. null
파일을 찾을 수없는 경우 반환됩니다.
public static FileInfo FindApplicationFile(string fileName)
{
string startPath = Path.Combine(Application.StartupPath, fileName);
FileInfo file = new FileInfo(startPath);
while (!file.Exists) {
if (file.Directory.Parent == null) {
return null;
}
DirectoryInfo parentDir = file.Directory.Parent;
file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
}
return file;
}
참고 : Application.StartupPath
일반적으로 WinForms 응용 프로그램에서 사용되지만 콘솔 응용 프로그램에서도 작동합니다. 그러나 System.Windows.Forms
어셈블리에 대한 참조를 설정해야합니다 . 당신은 대체 할 수 Application.StartupPath
가
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
원하는 경우.
레벨 수를 선언하고 함수에 넣으려면 함수를 사용할 수 있습니까?
private String GetParents(Int32 noOfLevels, String currentpath)
{
String path = "";
for(int i=0; i< noOfLevels; i++)
{
path += @"..\";
}
path += currentpath;
return path;
}
다음과 같이 부를 수 있습니다.
String path = this.GetParents(4, currentpath);
이것은 도움이 될 수 있습니다
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
// file found
}
탐색하려는 폴더를 알고 있으면 해당 폴더의 색인을 찾은 다음 하위 문자열을 찾으십시오.
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
일부 가상 디렉터리가 있고 디렉터리 방법을 사용할 수 없습니다. 그래서 관심있는 사람들을 위해 간단한 분할 / 결합 기능을 만들었습니다. 그래도 안전하지는 않습니다.
var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
따라서 4 개를 위로 이동하려면를로 변경하고 예외를 피하기 위해 몇 가지 검사를 추가 하면 1
됩니다 4
.
참고URL : https://stackoverflow.com/questions/14899422/how-to-navigate-a-few-folders-up
'IT박스' 카테고리의 다른 글
Objective-C에서 예를 들어 밀리 초 단위로 정확한 시간을 어떻게 얻을 수 있습니까? (0) | 2020.08.23 |
---|---|
배열이 비어 있는지 또는 null인지 확인 (0) | 2020.08.23 |
image.onload 이벤트 및 브라우저 캐시 (0) | 2020.08.22 |
Android 작업 선호도 설명 (0) | 2020.08.22 |
Git에서 commit-ish와 tree-ish는 무엇입니까? (0) | 2020.08.22 |