writing file to disk from embedded resource

k3n51mm

Active member
Joined
Mar 7, 2007
Messages
40
Programming Experience
3-5
I have an application that imports XML files. If the DTD for the incoming XML file is missing, I need to write it to the import directory and restart the import routine.

So, I am storing the DTD in the application as an embedded resource. I can get the DTD into a stream instance using the following code:

VB.NET:
'Get DTD from embedded resource
Dim assy As Assembly = Assembly.GetExecutingAssembly()
Dim manifestResource As String = String.Empty
manifestResource = "myapp.GENERAL_1.dtd"
Dim strDTD As Stream = assy.GetManifestResourceStream(manifestResource)

Now that I have the DTD into a stream, how do I write it to a file on disk?
Do I need a filestream + writer, or what? It's been too long since I did this.
 
Here is the solution, in case anyone comes looking:
VB.NET:
'Get DTD from embedded resources
Dim assy As Assembly = Assembly.GetExecutingAssembly()
Dim manifestResource As String = String.Empty
manifestResource = "GENERAL_1.dtd"
Dim strDTD As Stream = assy.GetManifestResourceStream(manifestResource)
' Read the stream into encoded utf-8 format
Dim encDTD As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim readStream As New StreamReader(strDTD, encDTD)
Dim szDTD As String = ""
While (readStream.Peek() > -1)
szDTD += readStream.ReadLine() + vbCrLf
End While
Dim szFilePath As String = "GENERAL_1.dtd"
Dim fsDTD As New FileStream(szFilePath, FileMode.Create, FileAccess.Write)
Dim wrtrDTD As New StreamWriter(fsDTD)
wrtrDTD.Write(szDTD)
strDTD.Close()
wrtrDTD.Close()
fsDTD.Close()
 
That can be done a little simpler:
VB.NET:
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] assy [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] Assembly = Assembly.GetExecutingAssembly()[/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] s [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] IO.Stream = assy.GetManifestResourceStream([/SIZE][SIZE=2][COLOR=#a31515]"resourcename"[/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] bytes(s.Length - 1) [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Byte[/COLOR][/SIZE]
[SIZE=2]s.Read(bytes, 0, s.Length)[/SIZE]
[SIZE=2][COLOR=#0000ff]My[/COLOR][/SIZE][SIZE=2].Computer.FileSystem.WriteAllBytes([/SIZE][SIZE=2][COLOR=#a31515]"filename"[/COLOR][/SIZE][SIZE=2], bytes, [/SIZE][SIZE=2][COLOR=#0000ff]False[/COLOR][/SIZE][SIZE=2])[/SIZE]
You can also add it to the application resources instead, and save it to file like this:
VB.NET:
[SIZE=2][COLOR=#0000ff]My[/COLOR][/SIZE][SIZE=2].Computer.FileSystem.WriteAllText([/SIZE][SIZE=2][COLOR=#a31515]"filename"[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]My[/COLOR][/SIZE][SIZE=2].Resources.resourcename, [/SIZE][SIZE=2][COLOR=#0000ff]False[/COLOR][/SIZE][SIZE=2])[/SIZE]
 
Back
Top