Embedded Resources

Sometimes your assembly on runtime depends on a file, like a image or a simple text file. To manage this file, you could store its location in the application configuration file, and then load your file by reading its location from configuration. Another option is to embedded the file as a resource in your assembly and then use the following code snippet to load it.

System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream(“NameOfTheFile”);

Lets see an example. Suppose an assembly called Model.dll that requires a file called TextFile.txt that is part of the same visual studio project. First of all you should define that file as an embedded resource (properties->build action = embedded resource). Then in your code, when you need to access this file you can load it this way:

System.IO.Stream fileStream = this.GetType().Assembly.GetManifestResourceStream(“Model.TextFile.txt”);
System.IO.StreamReader sr = new System.IO.StreamReader(s);
string fileContent = sr.ReadToEnd();

Note that the name of the assembly has been appended to the of the file. One you have read the contents of the file, remember to close the stream



Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s