Have recently been plagued by absolute road strength and relative path problems, talk about my solution.
When we configure a road strength in XML, sometimes it is convenient to write relative paths, because it is not necessary to make any changes after porting to another computer, but the relative path written in XML is sometimes the path of IIS, for example, the WebService service we configure is published with IIS.
The speaker said no more, on the example:
1:
string P1 = @ "C:\A\B\C\D\E\F\G\H\";
string P2 = @ "C:\A\B\M\N\";
To find the relative path of P2 relative to the P1,
First manually, P1 from the back forward: H->g->f->e->d->c->b and then in the stitching on the P2, the conclusion should be:
String Relativepath= ".. \\.. \\.. \\.. \\.. \\.. \\M\\N ";
Is there a simple way to do it? Yes
Please see:
Class program
{
static void Main (string[] args)
{
string p1 = @ "C:\A\B\C\D\E\F\G\H\";
string P2 = @ "C:\A\B\M\N\";
Uri u1 = new Uri (P1, urikind.absolute);
Uri U2 = new Uri (P2, urikind.absolute);
Uri U3 = u1. Makerelativeuri (U2);//u2 relative to U1 URI
Console.WriteLine (U3. originalstring);
Console.read ();
}
Example 2:
String p3 = @ "C:\A\B\C\D\E\F\G\H\";
string P4 = ".. \\.. \\.. \\test.txt ";
P4 is a relative path, and the absolute path of P4 relative to P3 is obtained.
String p3 = @ "C:\A\B\C\D\E\F\G\H\";
string P4 = ".. \\.. \\.. \\X\\Y\\Z\\test.txt ";
Uri uri_p3 = new Uri (p3, urikind.absolute);
Uri uri_p4 = new Uri (P4, urikind.relative);
Uri Uri_result = new Uri (URI_P3, URI_P4);
The absolute path of Console.WriteLine ("P4 relative to P3" is: "+uri_result. LocalPath);
Console.read ();
Note: The absolute path URI object takes the path with LocalPath, and the relative path of the URI object takes the relative path with the originalstring
So when we fill in the complex relative path in the XML configuration, we don't have to worry about whether our relative path is relative to the program startup directory or the IIS directory. Read the relative path directly, and then convert it with a URI. Before I used the System.IO.Path class for various stitching, and finally ended in failure.
The above is a summary of personal experience.