I upgraded my old application in .Net 4.5. There are some obsolete methods warnings I was getting so thought to resolve them. One of the obsolete methods is XmlValidatingReader. Looked up on the internet and found that XmlReaderSettings is a potential alternate of XmlValidatingReader.
// ==old code==
Hashtable _SchemasCache = new Hashtable();
XmlReader xmlReader = new XmlTextReader(xmlStream);
XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader);
validatingReader.Schemas.Add(root.Namespace, schemaLocation); // both parametres are string. No error
_SchemasCache.Add(schemaLocation, validatingReader.Schemas);
// ==new code==
var schemaLocation = "res://somepath/Messages.xsd";
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(root.Namespace, schemaLocation); // this line gives error
_SchemasCache.Add(schemaLocation, settings.Schemas);
old code doesn't give any error but the new code gives an error of The URI prefix is not recognized.
I couldn't find the reason for this behavior of settings.Schemas.Add()
, as it is working fine with XmlValidatingReader
. Can anyone help with this?
Edit: Here value of schemaLocation is "res://somepath/Messages.xsd". Because schemaLocation has no Http:
or https://
or not a local resource
, that is why the error is occurring. How can I add schemas with these values using XmlReaderSettings
Edit 2: as this XSD is an embedded resource, I found some code online for this scenario. I made below code changes.
Assembly asm = Assembly.Load("AssemblyNameWhereXSDis");
Uri uri = new Uri(@"res://p.a.t.h/Autorisatie/Messages.xsd");
string resourceName1 = asm.GetName().Name + uri.AbsolutePath.Replace("/", ".");
using (Stream schemaStream = myAssembly.GetManifestResourceStream(resourceName1))
{
using (XmlReader schemaReader = XmlReader.Create(schemaStream)) // this line gives error : value(schemaStream) cannot be null
{
settings.Schemas.Add(root.Namespace, schemaReader);
}
}
here, the value of schemaStream
is null. And the value of resourceName1
is assemblyname.folder.Message.xsd
.
I have made Message.xsd
as Embedded Resource
from Visual Studio but still not working.