I have a file test.html on a relative path in c#:
string path1 = "/sites/site/folder/subfolder1/subfolder2/subfolder3/test.html";
Inside the file test.html I have a link to resource:
string path2 = "../../../subfolder4/image.jpg";
I want to calculate complete relative path to this resource against the same relative root as represented in path1 to get the following path3:
string path3 = CalculateRelativePath(path1, path2);
Assert.AreEqual(path3, "/sites/site/folder/subfolder4/image.jpg");
Are there any standard functions to do this? Thank you.
You can use this:
var page = new Uri(new Uri("http://dont-care"), path1);
var path3 = new Uri(page, path2).LocalPath;
I don't think there is a standard function to do this. You could write your own function, splitting both string paths to an array (using "/"), then using the array parts which equal ".." from one, to navigate up the other array.
Related
i have stucked on bellow problem in WPF C#.
Variable 'path' gets deserialized from xml file band contains following:
string path="D:\\test.mp4"
or
string path=#"D:\test.mp4"
uri i = new uri(path)
somehow path does not get recognized. Length is 12 instead of 11, i think because "\" does not get recongnized as path seperator. I have tried to sub string it and add it like this
string ss="D:" + #"\" + "test.mp4"
uri i = new uri(ss)
and still does not work. I tried with Path.combine also
Any idea?
I see you want to create a URI object and D:/test.mp4 is not a URI string. hence, try this to see if it works:
string path="file://D:/test.mp4"
uri i = new uri(path)
How to convert
"String path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
into
String path = #"C:\Abc\Omg\Why\Me\".
My approach is to first reverse the string and then remove all the "\" till we get first char, and the reverse it again.
How to do this in C#, is there any method for such operation?
You can just construct path using the Path static class:
string path = Path.GetFullPath(#"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\");
After this operation, variable path will contain the minimal version:
C:\Abc\Omg\Why\Me\
You can use path.TrimEnd('\\'). Have a look at the documentation for String.TrimEnd.
If you want the trailing slash, you can add it back easily.
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = path.TrimEnd('\\') + '\\';
another solution is
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = Path.GetFullPath(path);
I'm new to C# and struggle with string parsing. I have a string like this:
C:\User\Max\Pictures\
And I got multiple file paths:
C:\User\Max\Pictures\car.jpg
C:\User\Max\Pictures\trains\train.jpg
How can I strip the base path from those file paths to get:
car.jpg
trains\train.jpg
Something like this failed:
string path = "C:\\User\\Max\\Pictures\\";
string file = "C:\\User\\Max\\Pictures\\trains\\train.jpg";
string newfile = file.Substring(file.IndexOf(path));
You want to get the substring of file after the length of path:
string newfile = file.Substring(path.Length);
Note that it's a good idea to use Path methods like Path.GetFileName() when dealing with file paths (though it's not good applyable to the "train" example).
The other answer would be to replace your path with an empty string :
string filePath = file.Replace(path, "");
There are special classes to handle filepaths
var filePath = new FileInfo("dd");
In filePath.Name is the filename of the file whitout directory
So for your scenario you want to strip base dir. So you can do this
var filePath = new FileInfo(#"c:\temp\train\test.xml");
var dir = filePath.FullName.Replace(#"c:\temp", String.Empty);
There are many dupes for "appending a relative path to an absolute path", but I need to add relative to relative.
e.g.:
Path1 = "Parent/Child/a.txt"
Path2 = "../Sibling/file.cs"
Result = "Parent/Sibling/file.cs"
Tried:
Directory.GetParent() - works, but I can't find a way to return the result (it can only return absolute paths)
Path.Combine() - only works for simple cases and absolute paths. Fails (badly!) on the use of ".." with relative paths
...it seems absurd to write a string-tokenizing Path class to solve this, but I've been digging through the MSDN docs and can't seem to find a working Path/Directory class that correctly works with relative paths.
To make matters worse ... I'm trying to make this work all the way back to .NET 2 (thanks to Mono compatibilty)
I know the following code is ugly but will work (sorry I don't confirm on mono yet):
var Result =
Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path1), Path2))
.Substring(Directory.GetCurrentDirectory().Length + 1); // +1 to remove leading path separator
I'm not sure why you say Path.Combine fails badly, since you don't give any examples of what you've tried. But Path.Combine does exactly what you're looking for. You do have to give it a little help in this case; your first path is a filename, and you need the directory.
var filePath1 = "Parent/Child/a.txt";
var filePath2 = "../Sibling/file.cs";
var baseDirectory = Path.GetDirectoryName(filePath1);
var result = Path.Combine(baseDirectory, filePath2);
This returns "Parent\Child\../Sibling/file.cs" rather than the "Parent/Sibling/file.cs" you're looking for, but the two paths are exactly equivalent.
I tried this on Windows, it should work on Mac OS (Mono/Xamarin) or Linux (Mono) but you might need a different value for the dummyDriveLetter variable.
static void Main(string[] args)
{
string Path1 = "Parent/Child/a.txt";
string Path2 = "../Sibling/file.cs";
string dummyDriveLetter = "C:/"; // must be an absolute path, so let's add a dummy prefix, works on Windows
string absolutePath1 = dummyDriveLetter + Path1;
var path1Uri = new Uri(absolutePath1, UriKind.Absolute);
var path2Uri = new Uri(Path2, UriKind.Relative);
var diff = new Uri(path1Uri, path2Uri);
string Result = diff.OriginalString.Replace(dummyDriveLetter, "");
Console.WriteLine(Result);
}
If i have the following directory structure:
Project1/bin/debug
Project2/xml/file.xml
I am trying to refer to file.xml from Project1/bin/debug directory
I am essentially trying to do the following:
string path = Environment.CurrentDirectory + #"..\..\Project2\xml\File.xml":
what is the correct syntax for this?
It's probably better to manipulate path components as path components, rather than strings:
string path = System.IO.Path.Combine(Environment.CurrentDirectory,
#"..\..\..\Project2\xml\File.xml");
Use:
System.IO.Path.GetFullPath(#"..\..\Project2\xml\File.xml")
string path = Path.Combine( Environment.CurrentDirectory,
#"..\..\..\Project2\xml\File.xml" );
One ".." takes you to bin
Next ".." takes you to Project1
Next ".." takes you to Project1's parent
Then down to the file
Please note that using Path.Combine() might not give you the expected result, e.g:
string path = System.IO.Path.Combine(#"c:\dir1\dir2",
#"..\..\Project2\xml\File.xml");
This results in in the following string:
#"c:\dir1\dir2\dir3\..\..\Project2\xml\File.xml"
If you expect the path to be "c:\dir1\Project2\xml\File.xml", then you might use a method like this one instead of Path.Combine():
public static string CombinePaths(string rootPath, string relativePath)
{
DirectoryInfo dir = new DirectoryInfo(rootPath);
while (relativePath.StartsWith("..\\"))
{
dir = dir.Parent;
relativePath = relativePath.Substring(3);
}
return Path.Combine(dir.FullName, relativePath);
}