2

如何获取嵌入资源的资源 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
4

2 回答 2

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);
        }
于 2013-04-04T11:18:20.977 回答
2

作为一个快速简单的解决方案:

public static string GetPath(string relativeFileName)
{
    return Assembly.GetExecutingAssembly().GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(relativeFileName));
}
于 2013-04-04T10:58:53.740 回答