barmys scrap page

From Bohemia Interactive Community
Jump to navigation Jump to search
Retrieving File Data From Resource Bundles
It is possible to include files from a Visual Studio Solution INSIDE the .DLL file, in such away that they can be access by the code at runtime.
The is done by setting the “Build Action” for the file to “Embedded Resource”.
Resources are retrieved by name, a resource name are punctuated with DOTS and normally start with the fully qualified NAMESPACE at the beginning.
This can be useful if you have large lumps of text or binary data you want to use without providing an extra file. Possible reasons include:
  • Security you don’t want it read easily
  • Reliability you don’t want users meddling with it
  • Reducing configuration – you don’t have to decide and store the location of the file, esp. If the .DLL will be in the GAC
The code provided provides two features to make developers lives easier.
  • Replace ‘/’ or ‘\’ with ‘.’ In resource names.
  • Replace ‘~’ with the FQN of the Assemlby.
Allowing the developer to write things like “~/javascript.js” as a resourceName, eg.
string javascript = GetEmbeddedResource("~/javascript.js");
Except in the example below:
9 times out of ten the default Namespace and the AssemblyName are the same thing ( ie. Unless the programmer changes the project settings ). The AssemblyName is readily Available at runtime. Below the default namespace is “Blackmarble.Webparts”.
string javascript = GetEmbeddedResource("BlackMarble.WebParts.javascript.js");

/// &GT;summary<
/// Get the contents of an embedded resource file as a string.
/// &GT;/summary<
/// &GT;param name="resourceName"<&GT;/param<
/// &GT;returns<&GT;/returns<
internal static string GetEmbeddedResource(string resourceName) {

string sql = null;
try {
// assume we are in the "executing assembly" which contains the resource
Assembly executingAssembly = Assembly.GetExecutingAssembly();
// can't get the namespace easily, use the assembly name instead
string executingAssemblyName = executingAssembly.GetName().Name;
// do some search and replace to accept resourceNames which look more
// like filepaths.
resourceName = resourceName.Replace(@"~", executingAssemblyName);
resourceName = resourceName.Replace(@"\", @".");
resourceName = resourceName.Replace(@"/", @"."); // don't mention *nix.
Stream stream = executingAssembly.GetManifestResourceStream(resourceName);
if (stream == null) {
Debug.Assert(false, "missing resource");
} else {
StreamReader streamReader = new StreamReader(stream);
sql = streamReader.ReadToEnd();
} catch (Exception ex) {
return sql;