Freigeben über


A Simple Resource Helper Class

using

System;
using System.Reflection;
using System.IO;
using System.Runtime.CompilerServices;

///

<summary>
/// A simple helper class for extracting Resources from the
/// calling assembly
/// </summary>

public

class ResourceHelper
{
private static Stream GetStream(Assembly assembly, string ResourceName)
{
if (ResourceName != null && ResourceName.Trim() != string.Empty)
      {
ResourceName = ResourceName.Trim();
foreach (string name in assembly.GetManifestResourceNames())
if (string.Compare(ResourceName, name, true) == 0)
return assembly.GetManifestResourceStream(name);

         ResourceName = ResourceName.ToUpper();
foreach (string name in assembly.GetManifestResourceNames())
if (name.ToUpper().IndexOf(ResourceName) >= 0;
return assembly.GetManifestResourceStream(name);
      }

      return new MemoryStream(new byte[0], false);
   }

   /// <summary>
   /// Returns the requested resource as a Stream
   /// </summary>
   /// <param name="ResourceName">
   /// The name of the resource to retrieve
   /// </param>
   /// <returns>
   /// A stream for the requested resource on success.
   /// An empty stream on failure
   /// </returns>
   /// <remarks>
   /// GetStream first searches for an exact, case insensitive
   /// match to ResourceName. If the initial search fails,|
   /// GetStream will search again and return the first
   /// resource for which ResourceName is a case insensitive
   /// sub-string
   /// </remarks>
   [MethodImpl(MethodImplOptions.NoInlining)]
   public static Stream GetStream(string ResourceName)
   {
      return GetStream(Assembly.GetCallingAssembly(), ResourceName);
   }

   /// <summary>
   /// Returns the requested resource as a byte[]
   /// </summary>
   /// <param name="ResourceName">
   /// The name of the resource to retrieve
   /// </param>
   /// <returns>
   /// A byte[] for the requested resource on success.
   /// An empty byte[] on failure</returns>
   /// <remarks>
   /// GetBytes first searches for an exact, case insensitive
   /// match to ResourceName. If the initial search fails,
   /// GetBytes will search again and return the first
   /// resource for which ResourceName is a case insensitive
   /// sub-string
   /// </remarks>
   [MethodImpl(MethodImplOptions.NoInlining)]
   public static byte[] GetBytes(string ResourceName)
   {
      Stream s = GetStream(Assembly.GetCallingAssembly(), ResourceName);
      byte[] bytes = new byte[s.Length];
      s.Read(bytes, 0, bytes.Length);
      s.Close();
      return bytes;
   }
}

--- jeh
This post is provided “As Is”, with no warranties, and confers no rights.

Comments