如何获取嵌入资源的资源Uri?
我有一个如下方法,它根据xsd文件验证xml。此方法在MSTest中使用:
public static string Validate(string xml, string relativeXsdFilePath)
{
var schemas = new XmlSchemaSet();
// relativeXsdFilePath like 'TestData.Xsd.XsdFile1.xsd'
var schemaUri = ResourceHelper.GetPath(relativeXsdFilePath);
schemas.Add("", schemaUri);
XDocument doc = XDocument.Load(new StringReader(xml));
string msg = null;
doc.Validate(schemas, (o, e) =>
{
msg = e.Message;
});
return msg;
}
到目前为止,我没有成功实施以下方法!:
public static string GetPath(string relativeFileName)
{
var assemblyName = new AssemblyName(Assembly.GetExecutingAssembly().FullName).Name;
var resourceName = GetResourceName(relativeFileName);
// resource name would be like 'ProjectName.UnitTests.TestData.Xsd.profile.xsd'
var result = string.Format("/{0};component/{1}", assemblyName, resourceName);
return result;
}
我的XSD位于:
ProjectRoot
---TestData
------Xsd
---------XsdFile1.xsd
答案 0 :(得分:3)
我意识到它也接受了XmlReader所以这里是我的解决方案,如果有人会遇到同样的问题:
public static XmlReader LoadAsXmlReader(string relativeFileName)
{
var result = LoadAsStream(relativeFileName);
var xmlReader = new XmlTextReader(result);
return xmlReader;
}
private static Stream LoadAsStream(string relativeFileName)
{
var resourceFileName = Assembly
.GetExecutingAssembly()
.GetManifestResourceNames()
.FirstOrDefault(p => p.EndsWith(relativeFileName));
return Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(resourceFileName);
}
答案 1 :(得分:2)
作为一个快速简单的解决方案:
public static string GetPath(string relativeFileName)
{
return Assembly.GetExecutingAssembly().GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(relativeFileName));
}