한 가지 옵션은 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 upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, @"..\..\"));
