Read XSD from embedded resource with VB.NET
-
I'm reading xml from SQL server with VB.net using an XSD schema file. I have the code working fine, but I'd now like to change the code from reading a file on disk to reading the schema from the file as an embedded resource. Here's my code, what do I need to change??
Dim conString As String = "MyConnectionString" Dim strm As Stream Dim strmReader As StreamReader Dim cmd As New SqlXmlCommand(conString) Dim xmlDoc As New XmlDocument Dim strXML As String With cmd .CommandText = "MyXPath" .CommandType = SqlXmlCommandType.XPath .SchemaPath = "C:\MySchemaFile.xsd" '**I want this to be embedded!!** strm = .ExecuteStream End With strmReader = New StreamReader(strm) strXML = strmReader.ReadToEnd xmlDoc.LoadXml(strXML)
Like I said, the above code works fine, but I don't want a physical file location. Thanks!!! -Michael -
I'm reading xml from SQL server with VB.net using an XSD schema file. I have the code working fine, but I'd now like to change the code from reading a file on disk to reading the schema from the file as an embedded resource. Here's my code, what do I need to change??
Dim conString As String = "MyConnectionString" Dim strm As Stream Dim strmReader As StreamReader Dim cmd As New SqlXmlCommand(conString) Dim xmlDoc As New XmlDocument Dim strXML As String With cmd .CommandText = "MyXPath" .CommandType = SqlXmlCommandType.XPath .SchemaPath = "C:\MySchemaFile.xsd" '**I want this to be embedded!!** strm = .ExecuteStream End With strmReader = New StreamReader(strm) strXML = strmReader.ReadToEnd xmlDoc.LoadXml(strXML)
Like I said, the above code works fine, but I don't want a physical file location. Thanks!!! -MichaelAdd the XSD to the project, change it's build type to Embedded Resource. You'll use the Namespace to get at it. For example, if your assembly default namespace is
MyDataAccess
, the resource base name will beMyDataAccess.MySchemaFile.xsd
. You'd useAssembly.GetExecutingAssembly().GetManifestResourceStream
to load it. Unfortunately,SqlXmlCommand
only accepts paths to theSchemaPath
So, you embed the XSD, then write it out as a temporary file, use it, and delete the temporary file:// excuse the C# string tmpFilePath = Path.GetTempFileName(); try { TextReader rdr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("MyDataAccess.MySchemaFile.xsd"); TextWriter wr = new StreamWriter(tmpFilePath, false); wr.WriteLine(rdr.ReadToEnd()); wr.Close(); rdr.Close(); // now tmpFilePath can be used in your SqlXmlCommand.SchemaPath until done, e.g., // cmd.SchemaPath = tmpFilePath; } catch (Exception e) { // handle the exception } finally { // get rid of that temp file! if (File.Exists(tmpFilePath)) File.Delete(tmpFilePath); }
Ian Mariano - http://www.ian-space.com/
"We are all wave equations in the information matrix of the universe" - me