一、将绝对路径转换成相对路径:
// 需要转换的绝对路径 string targetPath = "C:/test.txt"; // 相对路径对应的基准绝对路径 string sourcePath = Application.ExecutablePath; // 构造Uri对象 Uri sourceUri = new Uri(sourcePath); Uri targetUri = new Uri(targetPath); // 获取绝对路径对应的相对路径 targetUri = sourceUri.MakeRelativeUri(targetUri); targetPath = targetUri.ToString(); // 将相对路径反编码为本地路径格式 targetPath = HttpUtility.UrlDecode(targetPath); // 返回相对路径 return targetPath;
二、将相对路径转换成绝对路径:
// 需要转换的相对路径 string targetPath = "./../test.txt"; // 相对路径对应的基准绝对路径 string sourcePath = Application.ExecutablePath; // 获取当前工作目录 string tempPath = Environment.CurrentDirectory; // 设置当前工作目录为基准绝对路径所在目录 Environment.CurrentDirectory = Path.GetDirectoryName(sourcePath); // 获取相对路径对应的绝对路径 targetPath = Path.GetFullPath(targetPath); // 还原当前工作目录 Environment.CurrentDirectory = tempPath; // 返回绝对路径 return targetPath;