How to get the content of Embedded file in assembly?

Poster
Posted by Poster under C# category on | Views : 4150
First, to make a file(like .xml, .html, .jpg or .gif) embedded into the assembly so that when building the project it is included into the .dll of the project, you need to go to Properties of the file and select "Build Action" property to "Embeded Resources".

To get the content of the Embedded resources into your class, you can write following code in C#.

        /// <summary>
/// Get conntent of the embeded resources
/// </summary>
/// <param name="resourceName"></param>
/// <returns></returns>
public static Stream GetEmbeddedResourceContent(string resourceName)
{
try
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(Class1));
Stream str = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + resourceName);

if (str == null)
throw new Exception("Could find the embedded resource '" + resourceName + "'");
return str;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}


In VB.NET, you can write following code.


''' <summary>
''' Get conntent of the embeded resources
''' </summary>
''' <param name="resourceName"></param>
''' <returns></returns>
Public Shared Function GetEmbeddedResourceContent(resourceName As String) As Stream
Try
Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetAssembly(GetType(Class1))
Dim str As Stream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + resourceName)

If str = Nothing Then
Throw New Exception("Could find the embedded resource '" + resourceName + "'")
End If
Return str
Catch e As Exception
Throw New Exception(e.Message)
End Try
End Function


Thanks

Comments or Responses

Login to post response