65 lines
1.8 KiB
C#
65 lines
1.8 KiB
C#
using System.IO;
|
|
|
|
namespace JD.Guinness.WPF.Module.Extension
|
|
{
|
|
public static class StringExtension
|
|
{
|
|
public static string ToRelativePath(this string filePath, string basePath)
|
|
{
|
|
if (string.IsNullOrEmpty(filePath))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
string result = string.Empty;
|
|
int offset;
|
|
|
|
if (filePath.StartsWith(basePath))
|
|
{
|
|
return filePath.Substring(basePath.Length + 1);
|
|
}
|
|
|
|
string[] baseDirs = basePath.Split(new char[] { ':', '\\', '/' });
|
|
string[] fileDirs = filePath.Split(new char[] { ':', '\\', '/' });
|
|
|
|
if (baseDirs.Length == 0 || fileDirs.Length == 0 || baseDirs[0] != fileDirs[0])
|
|
{
|
|
return filePath;
|
|
}
|
|
|
|
for (offset = 1; offset < baseDirs.Length; offset++)
|
|
{
|
|
if (baseDirs[offset] != fileDirs[offset])
|
|
break;
|
|
}
|
|
|
|
for (int i = 0; i < (baseDirs.Length - offset); i++)
|
|
{
|
|
result += "..\\";
|
|
}
|
|
|
|
for (int i = offset; i < fileDirs.Length - 1; i++)
|
|
{
|
|
result += fileDirs[i] + "\\";
|
|
}
|
|
|
|
result += fileDirs[fileDirs.Length - 1];
|
|
|
|
return result;
|
|
}
|
|
|
|
public static string FromDifferentDirectory(this string filePath, string directoryPath)
|
|
{
|
|
if (!string.IsNullOrEmpty(filePath))
|
|
{
|
|
string newFilePath = Path.Combine(directoryPath, Path.GetFileName(filePath));
|
|
if (File.Exists(newFilePath))
|
|
{
|
|
return newFilePath;
|
|
}
|
|
}
|
|
|
|
return filePath;
|
|
}
|
|
}
|
|
}
|