4
lis/090
lis/090
[.NET] Relative path
Below is a quick and dirty implementation of solution for how to get relative path to file from a folder
Problem1:
Path1 (base): C:\data\my_path
Path2 (target): C:\some_other\folder\data\file.txt
Result: ..\..\some_other\folder\data\file.txt
Problem2:
Path1 (base): C:\data\path
Path2 (target): C:\data\path\somedata\file.txt
Result: .\somedata\file.txt
Solution:
public static string getRelativePath(String baseDirectory, string destinationFile)
{
List<String> _from = new List<String>(baseDirectory.Split('\\'));
List<String> _dest = new List<String>(destinationFile.Split('\\'));
if (_from[0].ToLower() != _dest[0].ToLower() || _dest.Count==0 || _from.Count==0)
{
return destinationFile; //Not same disk
}
int lvl = 0;
for(int i=0; i<_from.Count; i++)
{
if (_from[i].ToLower() != _dest[i].ToLower())
{
break;
}
lvl++;
}
for (int j = 0; j < lvl; j++)
{
_from.RemoveAt(0);
_dest.RemoveAt(0);
}
String _resultPath = "";
if (_from.Count == 0) //the file is in higher folder
{
_resultPath += ".\\";
for (int i = 0; i < _dest.Count; i++)
{
_resultPath += _dest[i];
if (i + 1 < _dest.Count)
_resultPath += "\\";
}
}
else
{
for (int i = 0; i < _from.Count; i++)
{
_resultPath += "..\\";
}
for (int i = 0; i < _dest.Count; i++)
{
_resultPath += _dest[i];
if (i + 1 < _dest.Count)
_resultPath += "\\";
}
}
return _resultPath;
}
Komentarze (0)
Trackbacks (0) ( subskrybuj komentarze w tej wiadomości )
Brak komentarzy.
Przepraszam, dodawanie komentarzy zablokowane.
Brak trackbacków.