Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何组合两条路径?_C#_Xml_Path_Filenames - Fatal编程技术网

C# 如何组合两条路径?

C# 如何组合两条路径?,c#,xml,path,filenames,C#,Xml,Path,Filenames,我有一个XmlTextReader来读取一系列XML文件,以便将一些信息加载到我的程序中 但是,在一些XML文件中,我有一个图像的文件名,我想加载该图像 但问题是XML文件没有图像的完整路径 <Image id="ImageId" File="Image.bmp" /> <!-- full path is not available. Image is behind XML--> 如何将路径与图像的路径相结合 我试过以下方法: string FullImagePath

我有一个XmlTextReader来读取一系列XML文件,以便将一些信息加载到我的程序中

但是,在一些XML文件中,我有一个图像的文件名,我想加载该图像

但问题是XML文件没有图像的完整路径

<Image id="ImageId" File="Image.bmp" /> 
<!-- full path is not available. Image is behind XML-->
如何将
路径
与图像的路径相结合

我试过以下方法:

string FullImagePath = Path.Combine(reader.BaseURI, imagePath);
这些是变量的值:

  • reader.BaseURI
    “file:///D:/.../currentXml.xml“
  • imagePath
    “Image.bmp”
  • 最后,
    FullImagePath
    ,在分配了
    Path.Combine的结果后,
    file:///D:/.../currentXml.xml\\Image.bmp
    ,这不是我所期望的
图像的预期路径为:
D:/…/image.bmp
,位于与
currentXml.xml
相同的目录中


那么如何获取图像文件的路径呢?

您有两个不同的问题需要分别解决

 Path.Combine(Path.DirectoryName(reader.BaseUri), imagePath)
根据用于使用图像文件的API,可能支持或不支持
文件://
URI路径。因此,您希望将其设置为本地路径,如中所述:

然后,您需要构建图像文件的路径,该文件与XML文件位于同一目录中

一种方法是获取文件所在的目录,请参见:

然后,您可以添加图像的文件名:

string imagePath = Path.Combine(xmlDirectory, "image.png"); // C:\Temp\image.png
或者,在“一”行中:


当您处理解析URL时,我建议在
System.Xml
中使用
XmlUrlResolver

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

请注意,如果要从URI中删除“file://”方案,请查看URI类和AbsolutePath属性。我使用
Path.Combine(Path.GetDirectoryName(reader.BaseURI)、imagePath)修复了它。子字符串(6)
因为
file://
的长度始终相同。thanksI强烈建议使用框架方法删除该方案。.substring(6)不明显,可能会中断。(至少从BaseUri中删除该方案,因为如果imagePath中提供了根路径或绝对路径,这可能会创建无效路径。感谢您的解释。
GetDirectoryName
完成了这项工作。但是为了摆脱
文件://
我使用了
子字符串(6)
。不漂亮但简单,代码不仅“不漂亮”,总有一天也会中断。谢谢。接受。一行解决方案。
newURI(Path.Combine(Path.GetDirectoryName(reader.BaseURI),ImagePath)).LocalPath
。现在它总有一天会坏的!@M.kazemAkhgary MSDN,所以我怀疑它是否会起作用。Edit:它似乎能起作用……它确实能起作用,但不受支持,因此可能会在任何.NET版本中改变工作方式。您喜欢的合适的“一行程序”是
字符串imagePath=Path.Combine(Path.GetDirectoryName(新Uri(reader.BaseURI.LocalPath),ImagePath);
string xmlDirectory = Path.GetDirectoryName(xmlLocalPath); // C:\Temp
string imagePath = Path.Combine(xmlDirectory, "image.png"); // C:\Temp\image.png
string imagePath = Path.Combine(Path.GetDirectoryName(new Uri(reader.BaseURI).LocalPath), 
                                ImagePath);
string localPath = new XmlUrlResolver().ResolveUri(new Uri(baseUri), imageName).LocalPath;