M.kazem Akhgary
M.kazem Akhgary

Reputation: 19179

How to Combine Two paths?

I have an XmlTextReader to read series of XML files to load some information in to my program.

However, in some XML files I have the file name of an image and I want to load that image.

But the problem is the XML file does not have the full path of the image.

<Image id="ImageId" File="Image.bmp" /> 
<!-- full path is not available. Image is behind XML-->

This means the Image exist where the xml file exists.

for some reason, the only way to get the path of the XML file is to get the path of the XmlTextReader reading the current XML file.

I did some research and I found out you can retrieve the XML path from the XmlTextReader as below:

string path = reader.BaseURI; // this will get the path of reading XML
                              // reader is XmlTextReader

How can I combine path with the image's path?

I have tried the following way:

string FullImagePath = Path.Combine(reader.BaseURI, imagePath);

These are the values of the variables:

Expected path of the image is: D:/.../Image.bmp, in the same directory as currentXml.xml.

So how can I get the path of the image file?

Upvotes: 0

Views: 1970

Answers (3)

Martin Honnen
Martin Honnen

Reputation: 167716

As you are dealing with resolving URLs I would suggest to use XmlUrlResolver in System.Xml:

string localPath = new XmlUrlResolver().ResolveUri(new Uri(baseUri), imageName).LocalPath;

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151720

You have a two different problems that you need to solve separately.

Depending on the API used to consume the image file, a file:// URI path may or may not be supported. So you'd want to make that a local path as explained in Convert file path to a file URI?:

string xmlPath = "file://C:/Temp/Foo.xml";
var xmlUri = new Uri(xmlPath); // Throws if the path is not in a valid format.
string xmlLocalPath = xmlUri.LocalPath; // C:\Temp\Foo.xml

Then you want to build the path to the image file, which resides in the same directory as the XML file.

One way to do that is to get the directory that file is in, see Getting the folder name from a path:

string xmlDirectory = Path.GetDirectoryName(xmlLocalPath); // C:\Temp

Then you can add your image's filename:

string imagePath = Path.Combine(xmlDirectory, "image.png"); // C:\Temp\image.png

Or, in "one" line:

string imagePath = Path.Combine(Path.GetDirectoryName(new Uri(reader.BaseURI).LocalPath), 
                                ImagePath);

Upvotes: 1

Matthew Whited
Matthew Whited

Reputation: 22443

 Path.Combine(Path.DirectoryName(reader.BaseUri), imagePath)

Upvotes: 1

Related Questions