本文整理汇总了C#中System.Reflection.Assembly.GetManifestResourceNames方法的典型用法代码示例。如果您正苦于以下问题:C# Assembly.GetManifestResourceNames方法的具体用法?C# Assembly.GetManifestResourceNames怎么用?C# Assembly.GetManifestResourceNames使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Reflection.Assembly
的用法示例。
在下文中一共展示了Assembly.GetManifestResourceNames方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExtractResource
public void ExtractResource(string resourceName, string fullFileName, Assembly assembly)
{
_logger.Trace("Attempting to extract " + resourceName + "...");
string[] names = assembly.GetManifestResourceNames();
string resource = names.FirstOrDefault(x => x.Contains(resourceName));
if (resource == null)
{
throw new MissingManifestResourceException(resourceName);
}
Stream resourceStream = assembly.GetManifestResourceStream(resource);
Stream fileStream = File.OpenWrite(fullFileName);
byte[] buffer = new byte[resourceStream.Length];
resourceStream.Read(buffer, 0, buffer.Length);
fileStream.Write(buffer, 0, buffer.Length);
resourceStream.Close();
fileStream.Close();
_logger.Trace(resourceName + " extracted to " + fullFileName + ".");
}
示例2: GetBitmapFromEmbeddedResource
public Bitmap GetBitmapFromEmbeddedResource(string resourceName, Assembly asm)
{
var original = resourceName;
var keyName = asm.GetManifestResourceNames().FirstOrDefault(p => p.EndsWith(resourceName)) ??
asm.GetManifestResourceNames().FirstOrDefault(p => p.EndsWith(original));
if (keyName == null)
return null;
return new Bitmap(asm.GetManifestResourceStream(keyName));
}
示例3: ReadEmbeddedResourceTextContents
public string ReadEmbeddedResourceTextContents(string resourceName, Assembly assembly = null)
{
Trace.Assert(!String.IsNullOrWhiteSpace(resourceName));
if (assembly == null) assembly = Assembly.GetExecutingAssembly();
Trace.Assert(Array.IndexOf(assembly.GetManifestResourceNames(), resourceName) >= 0, String.Join(", ", assembly.GetManifestResourceNames()));
using(Stream s = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader sr = new StreamReader(s))
{
return sr.ReadToEnd();
}
}
}
示例4: GetPresetting
static public Preset[] GetPresetting(Assembly asmbl)
{
List<Preset> result = new List<Preset>();
foreach (string item in asmbl.GetManifestResourceNames())
{
ManifestResourceInfo resInfo = asmbl.GetManifestResourceInfo(item);
if (resInfo == null) continue;
using (Stream stream = asmbl.GetManifestResourceStream(item))
{
if (stream == null) continue;
if (item.Contains(".Resource.") && item.EndsWith(".xml"))
{
try
{
Preset preset;
XmlSerializer serializer = new XmlSerializer(typeof(Preset));
using (XmlReader reader = XmlReader.Create(stream))
preset = (Preset)serializer.Deserialize(reader);
result.Add(preset);
}
catch (Exception)
{
}
}
}
}
return result.ToArray();
}
示例5: Add
public void Add(Assembly assembly)
{
var assemblyName = assembly.GetName().Name;
foreach (var resourcePath in assembly.GetManifestResourceNames())
{
var virtualPath = resourcePath;
if (ExcludeAssemblyNameFromPath && resourcePath.StartsWith(assemblyName))
{
virtualPath = resourcePath.Substring(assemblyName.Length).TrimStart('.');
}
var tokens = virtualPath.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length > 1) // Handle file extension
{
var extension = tokens.Last();
tokens = tokens.Take(tokens.Length - 1).ToArray();
tokens[tokens.Length - 1] += "." + extension;
}
virtualPath = this.VirtualPathSeparator + tokens.Aggregate((a, b) => CombineVirtualPath(a, b));
if (Resources.ContainsKey(virtualPath))
throw new ArgumentException(String.Format("Some resources use the same key: {0}", resourcePath));
Resources[virtualPath] = new EmbeddedResource(assembly, resourcePath, virtualPath);
}
}
示例6: Extract
public void Extract(Assembly assembly, string prefix, string outputDirectory)
{
Directory.CreateDirectory(outputDirectory);
foreach (var subDir in this.knownSubDirectories.Select(s => s.Value))
{
Directory.CreateDirectory(Path.Combine(outputDirectory, subDir));
}
foreach (string resourceName in assembly.GetManifestResourceNames().Where(r => r.StartsWith(prefix, StringComparison.Ordinal)))
{
string filename = resourceName.Substring(prefix.Length);
string subDirKey = this.knownSubDirectories.Keys
.Where(k => filename.StartsWith(k, StringComparison.Ordinal))
.OrderByDescending(p => p.Length) // This ensures we get the most qualified prefix
.FirstOrDefault();
if (subDirKey != null)
{
filename = Path.Combine(this.knownSubDirectories[subDirKey], filename.Substring(subDirKey.Length));
}
filename = Path.Combine(outputDirectory, filename);
IOHelpers.WriteResourceToFile(resourceName, filename, assembly);
}
}
示例7: GetResourceString
private static string GetResourceString(string name, Assembly originalAssembly)
{
string translatedHelpString = null;
string[] resourceNames = originalAssembly.GetManifestResourceNames();
for (int i = 0; i < resourceNames.Length; i++)
{
try
{
int lastDotResourcesString = resourceNames[i].LastIndexOf(".resources");
string resourceName = resourceNames[i].Remove(lastDotResourcesString);
ResourceManager manager = new ResourceManager(resourceName, originalAssembly);
translatedHelpString = manager.GetString(name);
}
catch (Exception)
{
// There is nothing we can do if this doesn't find the resource string. The only harm is that
// the help text that is registered will not be as helpful as could otherwise be. Not worth
// failing the entire installation process over.
}
if (!string.IsNullOrEmpty(translatedHelpString))
return translatedHelpString;
}
return "";
}
示例8: ReadEmbeddedResourceString
/// <summary>
/// Reads the embedded resource string.
/// </summary>
/// <param name="resourceName">
/// Name of the resource.
/// <para>
/// You don't need to fully qualify the resource name; This method will look up all available resource
/// strings and tries to find a match using the <see cref="string.EndsWith(string,StringComparison)"/>
/// method.
/// </para>
/// <para>
/// This means, that you can call this method just with the file name of the embedded resource.
/// </para>
/// </param>
/// <param name="assembly">The assembly which contains the embedded resource.</param>
/// <returns>The embedded resource as string.</returns>
/// <exception cref="System.InvalidOperationException">
/// This exception will be thrown when the resource could not be found.
/// </exception>
public static string ReadEmbeddedResourceString(string resourceName, Assembly assembly)
{
var nameList = assembly.GetManifestResourceNames();
var embeddedResourceName = nameList.FirstOrDefault(n => n.EndsWith(resourceName, StringComparison.InvariantCultureIgnoreCase));
if (string.IsNullOrEmpty(embeddedResourceName))
{
return null;
}
var result = string.Empty;
using (var stream = assembly.GetManifestResourceStream(embeddedResourceName))
{
if (stream == null)
{
var error = string.Format(
CultureInfo.InvariantCulture,
"Cannot find embedded resource '{0}({2})' in assembly '{1}'",
resourceName,
assembly.FullName,
embeddedResourceName);
throw new InvalidOperationException(error);
}
using (var sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result;
}
示例9: Embedded
/// <summary>
/// Serves embedded resources of specified assembly.
/// </summary>
/// <param name="app">The application to extend.</param>
/// <param name="urlPrefix">The url prefix.</param>
/// <param name="assembly">The assembly to get resources from.</param>
/// <param name="resourcePrefix">The name prefix of embedded resource.</param>
public static ExpressApplication Embedded(this ExpressApplication app,
string urlPrefix, Assembly assembly, string resourcePrefix)
{
if (app == null) throw new ArgumentNullException("app");
if (assembly == null) throw new ArgumentNullException("assembly");
assembly
.GetManifestResourceNames()
.Where(s => s.StartsWith(resourcePrefix))
.ToList()
.ForEach(name =>
{
var path = name.Substring(resourcePrefix.Length);
app.Get(Combine(urlPrefix, path), req =>
{
using (var rs = assembly.GetManifestResourceStream(name))
{
req.ContentTypeByPath(name);
req.SendStream(rs);
}
});
});
return app;
}
示例10: FindAssembliesToExtract
private static Dictionary<string, AssemblyToExtract> FindAssembliesToExtract(Assembly currentAssembly, HashSet<string> assembliesToFind)
{
var resources = currentAssembly.GetManifestResourceNames();
var assembliesToExtract = new Dictionary<string, AssemblyToExtract>();
foreach (var resource in resources)
{
if (!resource.StartsWith("costura"))
continue;
var compressed = false;
var assembly = assembliesToFind.FirstOrDefault(x => resource.EndsWith(x + CompressedAssemblySuffix, StringComparison.InvariantCultureIgnoreCase));
if (assembly != null)
compressed = true;
else
assembly = assembliesToFind.FirstOrDefault(x => resource.EndsWith(x + AssemblySuffix, StringComparison.InvariantCultureIgnoreCase));
if (assembly == null)
continue;
assembliesToExtract.Add(resource, new AssemblyToExtract { Compressed = compressed, Name = assembly });
}
return assembliesToExtract;
}
示例11: AssemblyResourceMappingDescriptorProvider
public AssemblyResourceMappingDescriptorProvider(Assembly asm, string suffix)
{
List<string> files = new List<string>(asm.GetManifestResourceNames());
files = files.FindAll(delegate(string fileName) { return fileName.EndsWith(suffix); });
foreach (string file in files)
{
Stream resourceStream = null;
StreamReader reader = null;
try
{
resourceStream = asm.GetManifestResourceStream(file);
reader = new StreamReader(resourceStream);
string xmlMapping = reader.ReadToEnd();
AddMapping(xmlMapping);
}
catch (OtisException)
{
throw;
}
catch(Exception e)
{
throw new OtisException("Error while configuring mappings from assembly resource files.", e);
}
finally
{
if (reader != null) reader.Close();
if (resourceStream != null) resourceStream.Close();
}
}
}
示例12: GetEmbeddedFile
/// <summary>
/// Extracts an embedded file from the given assembly.
/// </summary>
/// <param name="assembly">The namespace of you assembly.</param>
/// <param name="fileName">The name of the file to extract. This need not be the full name.</param>
/// <returns>A stream containing the file data.</returns>
public static Stream GetEmbeddedFile(Assembly assembly, string fileName)
{
string assemblyFullName = assembly.FullName;
string assemblyName = assemblyFullName.Substring(0, assemblyFullName.IndexOf(","));
try
{
string resourceName = string.Empty;
string[] names = assembly.GetManifestResourceNames();
foreach (string name in names)
{
if (name.Contains(fileName))
{
resourceName = name;
break;
}
}
//System.Reflection.Assembly a = System.Reflection.Assembly.Load(assemblyName);
if (resourceName == string.Empty)
throw new Exception("Could not locate embedded resource '" + fileName + "' in assembly '" + assemblyName + "'");
Stream str = assembly.GetManifestResourceStream(resourceName);
if (str == null)
throw new Exception("Could not locate embedded resource '" + fileName + "' in assembly '" + assemblyName + "'");
return str;
}
catch (Exception ex)
{
throw new Exception(string.Format("{0} occurred while trying to get resource '{1}' from assembly {2}: {3}",
ex.GetType().FullName, fileName, assemblyName, ex.Message), ex);
}
}
示例13: ReleaseFolder
/// <summary>释放文件夹</summary>
/// <param name="asm"></param>
/// <param name="prefix"></param>
/// <param name="dest"></param>
/// <param name="overWrite"></param>
/// <param name="filenameResolver"></param>
public static void ReleaseFolder(Assembly asm, String prefix, String dest, Boolean overWrite, Func<String, String> filenameResolver)
{
if (asm == null) asm = Assembly.GetCallingAssembly();
// 找到符合条件的资源
String[] names = asm.GetManifestResourceNames();
if (names == null || names.Length < 1) return;
IEnumerable<String> ns = null;
if (prefix.IsNullOrWhiteSpace())
ns = names.AsEnumerable();
else
ns = names.Where(e => e.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
if (String.IsNullOrEmpty(dest)) dest = AppDomain.CurrentDomain.BaseDirectory;
if (!Path.IsPathRooted(dest))
{
String str = Runtime.IsWeb ? HttpRuntime.BinDirectory : AppDomain.CurrentDomain.BaseDirectory;
dest = Path.Combine(str, dest);
}
// 开始处理
foreach (String item in ns)
{
Stream stream = asm.GetManifestResourceStream(item);
// 计算filename
String filename = null;
// 去掉前缀
if (filenameResolver != null) filename = filenameResolver(item);
if (String.IsNullOrEmpty(filename))
{
filename = item;
if (!String.IsNullOrEmpty(prefix)) filename = filename.Substring(prefix.Length);
if (filename[0] == '.') filename = filename.Substring(1);
String ext = Path.GetExtension(item);
filename = filename.Substring(0, filename.Length - ext.Length);
filename = filename.Replace(".", @"\") + ext;
filename = Path.Combine(dest, filename);
}
if (File.Exists(filename) && !overWrite) return;
String path = Path.GetDirectoryName(filename);
if (!path.IsNullOrWhiteSpace() && !Directory.Exists(path)) Directory.CreateDirectory(path);
try
{
if (File.Exists(filename)) File.Delete(filename);
using (FileStream fs = File.Create(filename))
{
IOHelper.CopyTo(stream, fs);
}
}
catch { }
finally { stream.Dispose(); }
}
}
示例14: CheckAssembly
public static void CheckAssembly(Assembly target)
{
foreach (string resource in target.GetManifestResourceNames())
{
string ext = Path.GetExtension(resource).ToLower();
// Pluck the simple name of the resource out of
// the fully qualified string. tokens[tokens.Length - 1]
// is the file extension, also not needed.
// NB This works only for resource names that don't contain the period.
string[] tokens = resource.Split('.');
string name = tokens[tokens.Length - 2];
name = name.ToLower();
if (ext == ".bmp" || ext == ".gif" || ext == ".jpg" || ext == ".jpeg")
{
Bitmap bitmap = (Bitmap)Bitmap.FromStream(target.GetManifestResourceStream(resource));
bitmap.MakeTransparent(Color.White);
_bitmaps.Add(name, bitmap);
}
else if (ext == ".config" || ext == ".xml" || ext == ".txt" || ext == ".dll")
{
StreamReader sr = new StreamReader(target.GetManifestResourceStream(resource));
string fileText = sr.ReadToEnd();
_files.Add(name, fileText);
}
}
}
示例15: FindFullyQualifiedName
public static string FindFullyQualifiedName(string resourceName, out Assembly assemblyFoundIn, Assembly assembly = null)
{
var pattern = string.Format(@"(?:(?!{0}))\.{0}", resourceName);
if (assembly != null)
{
assemblyFoundIn = assembly;
return assembly
.GetManifestResourceNames()
.FirstOrDefault(m => Regex.IsMatch(m, pattern, RegexOptions.IgnoreCase));
}
else
{
var firstMatch = "";
var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(x => !x.IsDynamic);
foreach (var asm in assemblies)
{
firstMatch = asm.GetManifestResourceNames()
.FirstOrDefault(m => Regex.IsMatch(m, pattern, RegexOptions.IgnoreCase));
if (firstMatch != null)
{
assemblyFoundIn = asm;
return firstMatch;
}
}
assemblyFoundIn = null;
return firstMatch;
}
}