Embedding images
One day you might encounter a user who has done some cleaning (thouroughly) on his PC. Your program crashes because it can't find some necessary files...
A reinstall will do the trick, but there's a more user-friendly way to cope with 'deleters'.
I'm going to use images in my example, but you could do this with every file you want (since you'll be getting a Stream).
Add an image to your project and make sure to put the Build Action to Embedded Resource.
Now here's some code to retrieve the image, the function GetEmbeddedImagePath() will return the filename, the function GetEmbeddedImage() will return an Image object. They both need 1 parameter, the name of the image you want to retrieve.
Public Shared Function GetEmbeddedImagePath(ByVal imageName As String) As String
Dim f, fn As String
f = Application.StartupPath
If Not f.EndsWith("\") Then f &= "\"
f &= "Images\"
fn = f & imageName
If File.Exists(fn) Then
Return fn
Else
If Not Directory.Exists(f) Then
Directory.CreateDirectory(f)
End If
Dim s As Stream = GetExecutingAssembly.GetManifestResourceStream(GetExecutingAssembly.GetName.Name & "." & imageName)
If not s Is Nothing Then
Dim i As Image = Bitmap.FromStream(s)
i.Save(fn)
Return fn
End If
End If
Return Nothing
End Function
Public Shared Function GetEmbeddedImage(ByVal imageName As String) As Image
Dim fn As String = GetEmbeddedImagePath(imageName)
If Not fn Is Nothing Then
Return Image.FromFile(fn)
End If
Return Nothing
End Function
A reinstall will do the trick, but there's a more user-friendly way to cope with 'deleters'.
I'm going to use images in my example, but you could do this with every file you want (since you'll be getting a Stream).
Add an image to your project and make sure to put the Build Action to Embedded Resource.
Now here's some code to retrieve the image, the function GetEmbeddedImagePath() will return the filename, the function GetEmbeddedImage() will return an Image object. They both need 1 parameter, the name of the image you want to retrieve.
Public Shared Function GetEmbeddedImagePath(ByVal imageName As String) As String
Dim f, fn As String
f = Application.StartupPath
If Not f.EndsWith("\") Then f &= "\"
f &= "Images\"
fn = f & imageName
If File.Exists(fn) Then
Return fn
Else
If Not Directory.Exists(f) Then
Directory.CreateDirectory(f)
End If
Dim s As Stream = GetExecutingAssembly.GetManifestResourceStream(GetExecutingAssembly.GetName.Name & "." & imageName)
If not s Is Nothing Then
Dim i As Image = Bitmap.FromStream(s)
i.Save(fn)
Return fn
End If
End If
Return Nothing
End Function
Public Shared Function GetEmbeddedImage(ByVal imageName As String) As Image
Dim fn As String = GetEmbeddedImagePath(imageName)
If Not fn Is Nothing Then
Return Image.FromFile(fn)
End If
Return Nothing
End Function
0 Comments:
Post a Comment
<< Home