Path.absolute를 상대 경로 문자열과 결합합니다.
를 사용하여 상대 경로를 사용하여 Windows 경로에 가입하려고 합니다.
하지만,Path.Combine(@"C:\blah",@"..\bling")돌아온다C:\blah\..\bling대신C:\bling\.
제 상대 경로 해결기(너무 어렵지 않아야 하는)를 쓰지 않고 이 작업을 수행할 수 있는 방법을 아는 사람이 있습니까?
기능:
string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);
(결과: absolutePath="C:\bling.txt")
동작하지 않는 것
string relativePath = "..\\bling.txt";
Uri baseAbsoluteUri = new Uri("C:\\blah\\");
string absolutePath = new Uri(baseAbsoluteUri, relativePath).AbsolutePath;
(결과: absolutePath="C:/blah/bling.txt")
콜 패스결합된 경로 http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx의 GetFullPath
> Path.GetFullPath(Path.Combine(@"C:\blah\",@"..\bling"))
C:\bling
(Path에 동의합니다.이것은 콤바인이 알아서 해야 합니다.)
Path.GetFullPath(@"c:\windows\temp\..\system32")?
Windows 유니버설 앱용Path.GetFullPath()사용할 수 없습니다.System.Uri대신 클래스:
Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
Console.WriteLine(uri.LocalPath);
Path.GetFullPath()는 상대 경로에서는 동작하지 않습니다.
다음은 상대 경로와 절대 경로 모두에서 사용할 수 있는 솔루션입니다.Linux와 Windows 모두에서 동작하며,..텍스트의 선두에서 예상한 대로(정지 상태에서는 정규화됩니다).이 솔루션은 여전히Path.GetFullPath간단한 회피책으로 해결할 수 있습니다.
확장 방식이기 때문에 다음과 같이 사용합니다.text.Canonicalize()
/// <summary>
/// Fixes "../.." etc
/// </summary>
public static string Canonicalize(this string path)
{
if (path.IsAbsolutePath())
return Path.GetFullPath(path);
var fakeRoot = Environment.CurrentDirectory; // Gives us a cross platform full path
var combined = Path.Combine(fakeRoot, path);
combined = Path.GetFullPath(combined);
return combined.RelativeTo(fakeRoot);
}
private static bool IsAbsolutePath(this string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
return
Path.IsPathRooted(path)
&& !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)
&& !Path.GetPathRoot(path).Equals(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal);
}
private static string RelativeTo(this string filespec, string folder)
{
var pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) folder += Path.DirectorySeparatorChar;
var folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString()
.Replace('/', Path.DirectorySeparatorChar));
}
이렇게 하면 필요한 것을 정확하게 얻을 수 있습니다(패스가 존재할 필요는 없습니다).
DirectoryInfo di = new DirectoryInfo(@"C:\blah\..\bling");
string cleanPath = di.FullName;
백슬래시에 주의하여 잊지 마십시오(두 번 사용하지 마십시오).
string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);
절대 경로, 상대 경로 또는 URI 기반 경로를 모두 처리할 수 있는 단일 솔루션은 없는 것 같습니다.그래서 이렇게 썼어요.
public static String CombinePaths(String basepath, String relpath)
{
Stack<String> vs = new Stack<String>();
int i;
var s = basepath.Split('\\');
for (i = 0; i < s.Length; i++)
{
if (s[i] != "..")
{
if (s[i] != ".")
vs.Push(s[i]);
}
else
{
vs.Pop();
}
}
var r = relpath.Split('\\');
for (i = 0; i < r.Length; i++)
{
if (r[i] != "..")
{
if (r[i] != ".")
vs.Push(r[i]);
}
else
{
vs.Pop();
}
}
String ret = "";
var a = vs.ToArray();
i = a.Count() - 1;
while (i > 0)
{
ret += a[i].ToString();
ret += "\\";
i--;
}
ret += a[0].ToString();
return ret;
}
퍼포먼스를 향상시키거나 답변에 적용되는 숏컷을 자유롭게 적용하십시오(보통 C#에서는 일하지 않고 C++로 씁니다).
언급URL : https://stackoverflow.com/questions/670566/path-combine-absolute-with-relative-path-strings
'source' 카테고리의 다른 글
| SQL 쿼리로 특정 데이터베이스의 모든 테이블 이름을 가져오시겠습니까? (0) | 2023.04.08 |
|---|---|
| node.js 앱에서 exe 파일을 만드는 방법 (0) | 2023.04.08 |
| Select Unique와 Select Distinguish의 차이 (0) | 2023.04.08 |
| PowerShell에서 MD5 체크섬을 가져오는 방법 (0) | 2023.04.08 |
| 사용자의 시간대 결정 (0) | 2023.04.08 |