GetManifestResourceNames() публичный Метод

Returns the names of all the resources in this assembly.
public GetManifestResourceNames ( ) : string[]
Результат string[]
        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
0
        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
0
        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
0
 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;
     }
 }
        public static IEnumerable<SqlCommand> GetSqlCommandsFromAssembly(Assembly assembly)
        {
            List<SqlCommand> result = new List<SqlCommand>();

            var resourceNames = Array.FindAll<string>(assembly.GetManifestResourceNames(), c =>
            {
                //return c.EndsWith(ConfigFilesProvider.CONFIG_FILE_EXTENSION);
                return ConfigFilesProvider.IsValidConfigFileName(c);
            });

            foreach (string resourceName in resourceNames)
            {
                using (Stream manifestResourceStream = assembly.GetManifestResourceStream(resourceName))
                {
                    using (StreamReader streamReader = new StreamReader(manifestResourceStream))
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        try
                        {
                            xmlDoc.Load(streamReader);
                            result.AddRange(ConfigFilesProvider.GetSqlCommandsFromXmlDoc(xmlDoc));
                        }
                        catch (Exception)
                        {

                        }

                    }
                }
            }

            return result;
        }
Пример #6
0
        /// <summary>
        ///     get the underlying streamreader for the resource
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="a">assembly.getexecutingassembly</param>
        /// <returns>make sure to close the streamreader if not null</returns>
        private static StreamReader GetResourceStream(string filename, Assembly a)
        {
            if (a == null || string.IsNullOrEmpty(filename))
                return null;

            try
            {
                var n = a.GetManifestResourceNames();
                var n1 = n.Where(s => s.EndsWith(filename));
                if (n1.Count() == 1)
                {
                    var s1 = n1.First();
                    var s2 = a.GetManifestResourceStream(s1);
                    if (s2 != null)
                    {
                        var s3 = new StreamReader(s2);
                        return s3;
                    }
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
Пример #7
0
 protected static string GetResourcePath(Assembly assembly, string path) {
     var resources = assembly.GetManifestResourceNames();
     var convertedPath = "." +
                         path.Replace("/", ".")
                             .Replace("\\", ".");
     return resources.Single(x => x.EndsWith(convertedPath));
 }
        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();
                }
            }
        }
        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 "";
        }
Пример #10
0
        private static void LoadResourceItems(string Folder, string entityName, string ConfigResourceDLL, string ConfigNamespace)
        {
            IConfigurationObject config = ConfigurationObjectFactory.CreateConfigurationObject(entityName);

            config.ClearAll();

            System.Reflection.Assembly configAssembly = System.Reflection.Assembly.Load(ConfigResourceDLL);

            var retVal = from item in configAssembly.GetManifestResourceNames()
                         where
                         (
                (item.ToLower().StartsWith(String.Format("{0}.{1}.", ConfigNamespace.ToLower(), Folder.ToLower()))) &&
                (item.ToLower().EndsWith(".xml"))
                         )
                         orderby item
                         select item
            ;

            List <string> items = retVal.ToList <string>();

            foreach (string item in items)
            {
                LoadResourceItem(Folder, entityName, ConfigNamespace, configAssembly, item);
            }
        }
Пример #11
0
        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);
                }
            }
        }
Пример #12
0
        /// <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;
        }
Пример #13
0
        /// <summary>
        /// Gets the embedded file identified by the resource name, and converts the
        /// file into a string.
        /// </summary>
        /// <param name="resourceName">In VS, is DefaultNamespace.FileName?</param>
        /// <returns></returns>
        public static string GetEmbeddedStringResource(Assembly assembly, string resourceName)
        {
            string result = null;

            // Use the .NET procedure for loading a file embedded in the assembly
            Stream stream = assembly.GetManifestResourceStream(resourceName);
            if (stream != null)
            {
                // Convert bytes to string
                byte[] fileContentsAsBytes = new byte[stream.Length];
                stream.Read(fileContentsAsBytes, 0, (int)stream.Length);
                result = Encoding.Default.GetString(fileContentsAsBytes);
            }
            else
            {
                // Embedded resource not found - list available resources
                Debug.WriteLine("Unable to find the embedded resource file '" + resourceName + "'.");
                Debug.WriteLine("  Available resources:");
                foreach (string aResourceName in assembly.GetManifestResourceNames())
                {
                    Debug.WriteLine("    " + aResourceName);
                }
            }

            return result;
        }
        /// <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);
            }
        }
Пример #15
0
        private static string LoadAllJavaScript()
        {
            System.Reflection.Assembly asm = typeof(U3Window).Assembly;
            string[]      names            = asm.GetManifestResourceNames();
            StringBuilder sb = new StringBuilder();

            byte[]      bytes    = new byte[1000];
            List <byte> allBytes = new List <byte>();

            foreach (string name in names.Where(name => name.EndsWith(".js")))
            {
                System.IO.Stream stream = asm.GetManifestResourceStream(name);
                int bytesRead           = stream.Read(bytes, 0, bytes.Length);
                if (bytesRead == bytes.Length)
                {
                    allBytes.AddRange(bytes);
                }
                else
                {
                    for (int i = 0; i < bytesRead; i++)
                    {
                        allBytes.Add(bytes[i]);
                    }
                }

                for (int i = 0; i < 2; i++)
                {
                    allBytes.Add((byte)'\n');
                }
            }

            string javascript = System.Text.Encoding.UTF8.GetString(bytes.ToArray());

            return(javascript);
        }
Пример #16
0
        /// <summary>
        /// Creates source files on disk from resources embedded in the supplied assembly
        /// </summary>
        /// <param name="resourceAssembly">Assembly containing the resources</param>
        /// <param name="rootResourceName">Root name for the resources that should be extracted</param>
        /// <param name="outputDir">The directory to which the source files should be extracted</param>
        /// <param name="replacementMap">List of placeholder and replacement values to substitute into the resources</param>
        /// <remarks>Only .java files will be extracted. The directory structure will be created on disk based
        /// on the separators in the resource name e.g. a resource called myorg.myapp.class1.java will be
        /// extracted into myorg\myapp\class1.java</remarks>
        public static void CreateSourceFiles(Assembly resourceAssembly, string rootResourceName, string outputDir, IDictionary<string, string> replacementMap)
        {
            string fixedRootResourceName = rootResourceName;
            if (!fixedRootResourceName.EndsWith("."))
            {
                fixedRootResourceName += ".";
            }

            // Unpack the source files into the sources directory
            foreach (string resourceName in resourceAssembly.GetManifestResourceNames().Where(n => n.EndsWith(".java")))
            {
                using (StreamReader reader = new StreamReader(resourceAssembly.GetManifestResourceStream(resourceName)))
                {
                    string content = reader.ReadToEnd();

                    // Substitute in the replacement tags
                    foreach (KeyValuePair<string, string> kvp in replacementMap)
                    {
                        content = content.Replace(kvp.Key, kvp.Value);
                    }

                    string newFilePath = CalculateSourceFilePath(fixedRootResourceName, resourceName, outputDir);

                    if (newFilePath != null)
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(newFilePath));
                        File.WriteAllText(newFilePath, content);
                    }
                }
            }

        }
Пример #17
0
        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;
        }
Пример #18
0
        /// <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(); }
            }
        }
 /// <summary>
 /// Return the fully qualified name of the resource file
 /// </summary>
 /// <param name="resourceFileName">File name of the resource</param>
 /// <returns></returns>
 private static string GetResourceFullName(string resourceFileName, Assembly assembly ) {
 
     foreach(var resource in assembly.GetManifestResourceNames())
         if(resource.EndsWith("."+resourceFileName))
             return resource;
     throw new System.ApplicationException("Resource '{0}' not find in assembly '{1}'".format(resourceFileName, Assembly.GetExecutingAssembly().FullName));
 }
        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);
            }
        }
Пример #21
0
        private static Func<NancyContext, string, Response> AddStaticResourcePath(string staticPath, Assembly assembly, string namespacePrefix)
        {
            return (context, s) =>
            {
                var path = context.Request.Path;
                var name = path.Replace('/', '.').TrimStart('.');
                var resourcePath = namespacePrefix + "." + staticPath;

                // Important to return null so that it passes through to the other resource providers
                if (!assembly.GetManifestResourceNames().Contains(resourcePath + "." + name))
                {
                    return null;
                }

                var response = new EmbeddedFileResponse(assembly, resourcePath, name);

                // Check ETag values to generate 304NotModified
                string currentFileEtag;
                if (response.Headers.TryGetValue("ETag", out currentFileEtag))
                {
                    if (context.Request.Headers.IfNoneMatch.Contains(currentFileEtag))
                    {
                        return new Response {StatusCode = HttpStatusCode.NotModified, ContentType = response.ContentType};
                    }
                }

                return response;
            };
        }
Пример #22
0
    private void Embedded()
    {
        // <Snippet3>
        System.Reflection.Assembly assem =
            System.Reflection.Assembly.LoadFrom(@".\MyLibrary.dll");
        System.IO.Stream fs =
            assem.GetManifestResourceStream("MyCompany.LibraryResources.resources");
        var rr = new System.Resources.ResourceReader(fs);

        // </Snippet3>

        if (fs == null)
        {
            Console.WriteLine(fs == null);
            foreach (var name in assem.GetManifestResourceNames())
            {
                Console.WriteLine(name);
            }

            return;
        }
        else
        {
            Console.WriteLine(fs == null);
        }
    }
Пример #23
0
 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();
 }
Пример #24
0
        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);
            }
        }
		public EmbeddedResourceFileSystem(Assembly assembly)
		{
			_assembly = assembly;
			_names = _assembly.GetManifestResourceNames().ToDictionary(s => Path.Combine(PathInfo.Create(s)), s => s);

			_etag = _assembly.GetName().Version.ToString(4);
		}
        /// <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;
        }
Пример #27
0
        // 리소스 dll 취득

        private static System.Reflection.Assembly ResolveAssembly(object sender, ResolveEventArgs args)
        {
            System.Reflection.Assembly thisAssembly = System.Reflection.Assembly.GetExecutingAssembly();

            string name = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll";

            var files = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(name));



            if (files.Count() > 0)
            {
                string fileName = files.First();

                using (System.IO.Stream stream = thisAssembly.GetManifestResourceStream(fileName))
                {
                    if (stream != null)
                    {
                        byte[] data = new byte[stream.Length];

                        stream.Read(data, 0, data.Length);

                        return(System.Reflection.Assembly.Load(data));
                    }
                }
            }

            return(null);
        }
Пример #28
0
        public TinyWebModule(Assembly assembly)
        {
            foreach (string resourceName in assembly.GetManifestResourceNames())
            {
                if (!resourceName.ToLower().Contains(".content."))
                    continue;

                string fileName = resourceName.Substring(resourceName.ToLower().IndexOf(".content.") + 9);

                content["/" + fileName] = new EmbeddedContent
                {
                    ResourceName = resourceName,
                    ContentTypeHeader = new ContentTypeHeader(GuessContentHeader(fileName)),
                    Assembly = assembly
                };

            }

            // json

            foreach (var type in assembly.GetTypes())
            {
                if (typeof(JsonService).IsAssignableFrom(type))
                {
                    foreach (var method in type.GetMethods())
                    {
                        var routes = method.GetCustomAttributes(typeof(RouteAttribute), false);
                        foreach (RouteAttribute route in routes)
                        {
                            content[route.Path] = new ActionRunner { Type = type, Action = method };
                        }
                    }
                }
            }
        }
Пример #29
0
        public static IEnumerable<DemoMetadata> GetDemos(Assembly sourceAssembly)
        {
            var resourceSets = from resourceName in sourceAssembly.GetManifestResourceNames()
                         let resourceStream = sourceAssembly.GetManifestResourceStream(resourceName)
                         select new ResourceSet(resourceStream);

              var bamlEntries = from set in resourceSets
                        from entry in set.Cast<DictionaryEntry>()
                        where entry.Key is string
                        where entry.Value is Stream
                        let value = new { Path = (string)entry.Key, Stream = (Stream)entry.Value }
                        where value.Path.EndsWith(".baml")
                        select value;

              var rootTypes = from entry in bamlEntries
                      let domObject = (XamlDomObject)XamlDomServices.Load(new Baml2006Reader(entry.Stream))
                      let demoName = domObject.GetAttatchedPropertyValueOrDefault<string>(DemoMetadataProperties.DemoNameProperty)
                      where demoName != null
                      let demoDescription = domObject.GetAttatchedPropertyValueOrDefault<string>(DemoMetadataProperties.DemoDescriptionProperty)
                      select new { Path = entry.Path, demoName, demoDescription };

              foreach (var entry in rootTypes) {
            var path = entry.Path.Replace(".baml", ".xaml");
            path = string.Format("/{0};component/{1}", sourceAssembly.GetName().Name, path);

            var uri = new Uri(path, UriKind.Relative);

            Func<FrameworkElement> factory = new Func<FrameworkElement>(() => {
              return (FrameworkElement)Application.LoadComponent(uri);
            });

            yield return new DemoMetadata(entry.demoName, entry.demoDescription, factory);
              }
        }
 public static void AddResourcesFromAssemblyToRegistry(Assembly assembly)
 {
     foreach (var item in assembly.GetManifestResourceNames())
     {
         resourceKeys.AddOrUpdate(item, assembly, (s, assembly1) => assembly);
     }
 }
Пример #31
0
        /// <summary>
        /// Creates and instance of BuildInformation class from the specified resource path in particular assembly.
        /// If assembly is null then BuildInformation for the whole framework is returned.
        /// If Path is null then the first found BUILD info resource is used form the specified assembly
        /// </summary>
        public BuildInformation(Assembly assembly, string path = null, bool throwError = true)
        {

          if (assembly == null)
          {
            assembly = Assembly.GetExecutingAssembly();
            path = FRAMEWORK_BUILD_INFO_PATH;
          }                                  

          if (path.IsNullOrWhiteSpace())
          {
            path = assembly.GetManifestResourceNames().FirstOrDefault(n=>n.EndsWith(BUILD_INFO_RESOURCE));
            if (path.IsNullOrWhiteSpace())
                path = FRAMEWORK_BUILD_INFO_PATH;
          }

          try
          {
            load(assembly, path);
          }
          catch (Exception error)
          {
            if (throwError)
                throw new ConfigException(StringConsts.BUILD_INFO_READ_ERROR + error.Message, error);
          }
        }
Пример #32
0
        public IImageWrapper GetIImageFromEmbeddedResource(string resourceName, Assembly asm)
        {
            var keyName = asm.GetManifestResourceNames().FirstOrDefault(p => p.EndsWith(resourceName));

            IImage imagingResource;
            var rstream = asm.GetManifestResourceStream(keyName);
            if(rstream is MemoryStream)
            {
                using(var strm = (rstream as MemoryStream))
                {
                    var pbBuf = strm.GetBuffer();
                    var cbBuf = (uint)strm.Length;
                    _factory.CreateImageFromBuffer(pbBuf, cbBuf, BufferDisposalFlag.BufferDisposalFlagNone, out imagingResource);
                }
            }else{
                using(var strm = rstream)
                {
                    var pbBuf = new byte[strm.Length];
                    strm.Read(pbBuf, 0, (int)strm.Length);
                    var cbBuf = (uint)strm.Length;
                    _factory.CreateImageFromBuffer(pbBuf, cbBuf, BufferDisposalFlag.BufferDisposalFlagNone, out imagingResource);
                }
            }
            return new IImageWrapper(imagingResource);
        }
Пример #33
0
        public static SqlScript[] ReadEmbeddedDirectory(Assembly assembly, String directory, bool absolutePath=false)
        {
            List<SqlScript> result = new List<SqlScript>();

            var internalDirectory = (absolutePath ? "" : assembly.GetName().Name + ".")  + directory.Replace("\\", ".").Trim('.') + ".";

            foreach (var file in assembly.GetManifestResourceNames())
            {
                if (file.EndsWith(".sql", StringComparison.InvariantCultureIgnoreCase)
                    && file.StartsWith(internalDirectory, StringComparison.InvariantCultureIgnoreCase))
                {
                    var fileName = file.Substring(internalDirectory.Length);

                    using (var fs = assembly.GetManifestResourceStream(file))
                    using (var sr = new StreamReader(fs))
                    {
                        var command = sr.ReadToEnd();
                        result.Add(new SqlScript
                        {
                            Name = fileName,
                            SQL = command
                        });
                    }
                }
            }
            return result.OrderBy(a=>a.Name).ToArray();
        }
Пример #34
0
 private void LoadResources()
 {
     _resources = new List <IResource>();
     foreach (String resourceName in _netAssembly.GetManifestResourceNames())
     {
         _resources.Add(new Resource(resourceName, _netAssembly, this));
     }
 }
Пример #35
0
 public static System.Collections.Generic.List <string> GetBuiltInStylesheets()
 {
     System.Reflection.Assembly executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
     return((
                from n in executingAssembly.GetManifestResourceNames()
                where n.StartsWith("MarkdownPad2.Stylesheets.")
                select n).ToList <string>());
 }
Пример #36
0
        /// <summary>
        /// Gets the resource names.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <returns></returns>
        public static string[] GetResourceNames(this Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }

            return(assembly?.GetManifestResourceNames());
        }
Пример #37
0
 private static System.IO.Stream getManifestResource(string resourceFilename)
 {
     System.Reflection.Assembly assembly = System.Reflection.Assembly.GetCallingAssembly();
     foreach (string resourceName in assembly.GetManifestResourceNames())
     {
         if (resourceName == resourceFilename || resourceName.EndsWith("/sfxframe85.js"))
         {
             return(assembly.GetManifestResourceStream(resourceName));
         }
     }
     System.Console.WriteLine("gzjs: failed to load resource %s", resourceFilename);
     return(null);
 }
 private void LoadAllResources(System.Reflection.Assembly assembly, string path)
 {
     foreach (string str in from name in assembly.GetManifestResourceNames()
              where name.StartsWith(path + ".", StringComparison.InvariantCultureIgnoreCase)
              select name)
     {
         using (Stream stream = assembly.GetManifestResourceStream(str))
         {
             byte[] buffer = new byte[stream.Length];
             stream.Read(buffer, 0, buffer.Length);
             string key    = str.Substring(path.Length + 1).Replace('.', Path.DirectorySeparatorChar);
             int    length = key.LastIndexOf(Path.DirectorySeparatorChar);
             if (length >= 0)
             {
                 key = key.Substring(0, length) + "." + key.Substring(length + 1);
             }
             base.Add(key, buffer);
         }
     }
 }
Пример #39
0
            /// <summary>
            /// Exporta os WSDLs e Schemas da DLL para as pastas do UniNFe
            /// </summary>
            public void load(Core.Empresa empresa)
            {
                List <ArquivoItem> ListArqsAtualizar = new List <ArquivoItem>();

                UpdateWSDL(ListArqsAtualizar);

                try
                {
                    System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom("NFe.Components.Wsdl.dll");
                    string[] x = ass.GetManifestResourceNames();
                    if (x.GetLength(0) > 0)
                    {
                        foreach (string s in x)
                        {
                            string fileoutput = null;
                            switch (Propriedade.TipoAplicativo)
                            {
                            case TipoAplicativo.Nfse:
                                if (s.StartsWith("NFe.Components.Wsdl.NFse."))
                                {
                                    fileoutput = s.Replace("NFe.Components.Wsdl.NFse.", Propriedade.PastaExecutavel + "\\");
                                }
                                break;
                            }

                            if (fileoutput == null)
                            {
                                continue;
                            }

                            if (fileoutput.ToLower().EndsWith(".xsd"))
                            {
                                /// Ex: NFe.Components.Wsdl.NFe.NFe.xmldsig-core-schema_v1.01.xsd
                                ///
                                /// pesquisa pelo nome do XSD
                                int plast = fileoutput.ToLower().LastIndexOf("_v");
                                if (plast == -1)
                                {
                                    plast = fileoutput.IndexOf(".xsd") - 1;
                                }

                                while (fileoutput[plast] != '.')
                                {
                                    --plast;
                                }

                                string fn = fileoutput.Substring(plast + 1);
                                fileoutput = fileoutput.Substring(0, plast).Replace(".", "\\") + "\\" + fn;
                            }
                            else
                            {
                                fileoutput = (fileoutput.Substring(0, fileoutput.LastIndexOf('.')) + "#" + fileoutput.Substring(fileoutput.LastIndexOf('.') + 1)).Replace(".", "\\").Replace("#", ".");
                            }

                            //fileoutput = fileoutput.Replace(NFe.Components.Propriedade.PastaExecutavel, "e:\\temp");
                            //System.Windows.Forms.MessageBox.Show(s + "\r\n"+fileoutput+"\r\n"+Path.GetFileName(fileoutput));
                            //continue;

                            FileInfo    fi   = new FileInfo(fileoutput);
                            ArquivoItem item = new ArquivoItem();
                            item = null;

                            if (fi.Exists)  //danasa 9-2013
                            {
                                if (ListArqsAtualizar.Count > 0)
                                {
                                    item = ListArqsAtualizar.FirstOrDefault(f => f.Arquivo == fi.Name);
                                }
                            }
                            // A comparação é feita (fi.LastWriteTime != item.Data)
                            // Pois intende-se que se a data do arquivo que esta na pasta do UniNFe for superior a data
                            // de quando foi feita a ultima atualizacao do UniNfe, significa que ele foi atualizado manualmente e não devemos
                            // sobrepor o WSDL ou SCHEMA do Usuario - Renan 26/03/2013
                            if (item == null || !(fi.LastWriteTime.ToString("dd/MM/yyyy") != item.Data.ToString("dd/MM/yyyy")))
                            {
                                if (item == null || !item.Manual)
                                {
                                    using (StreamReader FileReader = new StreamReader(ass.GetManifestResourceStream(s)))
                                    {
                                        if (!Directory.Exists(Path.GetDirectoryName(fileoutput)))
                                        {
                                            Directory.CreateDirectory(Path.GetDirectoryName(fileoutput));
                                        }

                                        using (StreamWriter FileWriter = new StreamWriter(fileoutput))
                                        {
                                            FileWriter.Write(FileReader.ReadToEnd());
                                            FileWriter.Close();
                                        }
                                    }
                                }
                            }
                            else if (item != null)
                            {
                                item.Manual = true;
                            }
                        }
                    }

                    GravarVersoesWSDLs(ListArqsAtualizar);
                }


                catch (Exception ex)
                {
                    Auxiliar.WriteLog(ex.ToString());
                }
            }
Пример #40
0
        /// <summary>
        /// header for the report
        /// </summary>
        /// <returns></returns>
        protected virtual string getHeader()
        {
            System.Reflection.Assembly thisApp = Assembly.GetExecutingAssembly();
            string[] inforesources             = thisApp.GetManifestResourceNames();
            Stream   file = null;

            foreach (string resourcename in inforesources)
            {
                if (resourcename.LastIndexOf("cas_logo.gif") > 0)
                {
                    file =
                        thisApp.GetManifestResourceStream(resourcename);
                }
            }
            if (file != null)
            {
                Image img = Image.FromStream(file);
                img.Save(Path.GetTempPath() + "\\cas_logo.gif");
            }

            //TODO: dopisac kopiowanie naszej ikony
            //      //bierzemy obrazek z resourcow
            //      System.Resources.ResourceManager rm = new System.Resources.ResourceManager("items",   System.Reflection.Assembly.GetExecutingAssembly());
            //      Object o=rm.GetObject ("cas_logo.gif");
            //      string destgif = System.IO.Path.GetTempFileName()+".gif";
            //      //BinaryWriter w = new BinaryWriter(fs);
            //
            //      using (BinaryWriter sw = new BinaryWriter(File.Create(DestFilename)))
            //      {
            //        sw.Write(o);
            //      }
            //
            //System.Drawing.Image.Bitmap image = (Bitmap)rm.GetObject ("cas_logo.gif");


            //wpisujemy nag³ówek
            return(@"
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>
<HTML>
<HEAD>
<title>" + reporttitle + " DateTime=" + m_DateTimeProvider.GetCurrentTime().ToString().Replace(":", "") + @"</title>
<meta http-equiv=Content-Type content='text/html; charset=windows-1250'>
<META NAME='Author' CONTENT='Maciej Zbrzezny'>
<META NAME='Keywords' CONTENT='report'>
<META NAME='Description' CONTENT='report'>
<style>
body{background:white;}
h1{text-decoration: none; font-family: times new roman; font-size:40px; color: #000000; font-weight: bold;}
h2{text-decoration: none; font-style: italic; font-family: times new roman; font-size:22px; color: #000000; font-weight: bold;}

table.tt{padding-right: 0.5cm; padding-left: 0.5cm; border-style: inset; border-color: none; background-color: none;}
table.t1{border-color: none; background-color: none;}
table.t2{border-style: inset; border-color: none; background-color: none;}

td.kk{padding-left: 1cm; font-family: times new roman, times; font-size:17px;}
td.k1{background-color:none ; text-decoration: none; font-family: times new roman, times; font-size:16px; color: #000000; font-weight: bold;}
td.k2{background-color:none ; text-decoration: none; font-family: times new roman, times; font-size:14px; color: #000000; font-weight: none;}
td.k3{background-color:#eeeee0 ; text-decoration: none; font-family: times new roman, times; font-size:12px; color: #000000; font-weight: bold;}
td.k4{background-color:none ; text-decoration: none; font-family: times new roman, times; font-size:12px; color: #000000; font-weight: none;}
td.k41{background-color:#eeeeeb ; text-decoration: none; font-family: times new roman, times; font-size:12px; color: #000000; font-weight: none;}
td.k5{background-color:#eeeee0 ; text-decoration: none; font-family: times new roman, times; font-size:16px; color: #000000; font-weight: bold;
</style>
</HEAD>
<BODY >
<table align='center' width='782' cellspacing='0' cellpadding='0' border='0' class='tt'>
<tr><td  bgcolor='#021376' width='782' height='1'></td></tr>
         ");
        }
Пример #41
0
 public string[] GetManifestResourceNames()
 {
     return(_assembly.GetManifestResourceNames());
 }
Пример #42
0
        //private static readonly object customDraw = new object();

        //[Description("Enables a tooltip's window to be custom painted.")]
        //public event ToolTipControllerCustomDrawEventHandler CustomDraw
        //{
        //    add { Events.AddHandler(customDraw, value); }
        //    remove { Events.RemoveHandler(customDraw, value); }
        //}

        public new virtual void OnCustomDraw(DevExpress.Utils.ToolTipControllerCustomDrawEventArgs e)
        {
            //base.OnCustomDraw(e);
            int       left = 16, top = 28;
            Font      f = e.ShowInfo.Appearance.Font;
            Rectangle r = e.Bounds;

            //r.Inflate(-1 * 6, -1 * 6);
            r = new Rectangle(left, top, r.Width - (left * 2), r.Height - 12);
            StringFormat format = new StringFormat();

            //e.Cache.DrawRectangle(new Pen(new SolidBrush(Color.Black), 1), r);

            if (e.ShowInfo.IconType != DevExpress.Utils.ToolTipIconType.None)
            {
                System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
                string resourceFile          = string.Empty;
                foreach (string resource in a.GetManifestResourceNames())
                {
                    if (resource.Contains("mgTooltipResources"))
                    {
                        resourceFile = resource;
                        break;
                    }
                }
                ResourceManager rm = new ResourceManager(resourceFile.Replace(".resources", ""), a);

                Image img = null;
                switch (e.ShowInfo.IconType)
                {
                case DevExpress.Utils.ToolTipIconType.Application:
                    img = (Image)rm.GetObject("application");
                    break;

                case DevExpress.Utils.ToolTipIconType.Asterisk:
                    img = (Image)rm.GetObject("asterisk");
                    break;

                case DevExpress.Utils.ToolTipIconType.Error:
                    img = (Image)rm.GetObject("error");
                    break;

                case DevExpress.Utils.ToolTipIconType.Exclamation:
                case DevExpress.Utils.ToolTipIconType.Warning:
                    img = (Image)rm.GetObject("warning");
                    break;

                case DevExpress.Utils.ToolTipIconType.Hand:
                    img = (Image)rm.GetObject("hand");
                    break;

                case DevExpress.Utils.ToolTipIconType.Information:
                    img = (Image)rm.GetObject("information");
                    break;

                case DevExpress.Utils.ToolTipIconType.Question:
                    img = (Image)rm.GetObject("question");
                    break;

                case DevExpress.Utils.ToolTipIconType.WindLogo:
                    img = (Image)rm.GetObject("windows");
                    break;

                case DevExpress.Utils.ToolTipIconType.None:
                    break;
                }

                if (img != null)
                {
                    Rectangle rImage = new Rectangle(r.Width - img.Width + r.Left, r.Top, img.Width, img.Height);
                    //e.Cache.DrawRectangle(new Pen(new SolidBrush(Color.Black), 1), rImage);
                    e.Cache.Graphics.DrawImage(img, rImage);
                }
            }

            if (!String.IsNullOrEmpty(e.ShowInfo.Title))
            {
                Font fTitle = new Font(f.Name, f.Size + 1, FontStyle.Bold);
                e.Cache.DrawString(e.ShowInfo.Title, fTitle, new SolidBrush(_titleForeColor), r, format);
                SizeF sizeTitle = e.Cache.Graphics.MeasureString(e.ShowInfo.Title, fTitle);
                top += (int)sizeTitle.Height + _titleSpacerHeight;
                r    = new Rectangle(r.X, top, r.Width, r.Height - (int)sizeTitle.Height - _titleSpacerHeight);
            }

            if (!String.IsNullOrEmpty(e.ShowInfo.ToolTip))
            {
                //e.Cache.DrawRectangle(new Pen(new SolidBrush(Color.Black), 1), r);
                e.Cache.DrawString(e.ShowInfo.ToolTip, f, new SolidBrush(_textForeColor), r, format);
            }

            e.Handled = true;

            // Throw the custom draw event
            //this.OnCustomDraw(e);
        }
Пример #43
0
        private static void RegisterDll(String moduleName, Boolean log = false)
        {
            String embedResourcePath         = "DXApplication";
            String embedResourceCategoryPath = "Path";
            String dllModuleName             = moduleName;
            String targetPath = null;

            #region 释放文件
            try
            {
                String targetFileName = String.Empty;
                String tempPath       = System.IO.Path.GetTempPath(); ////Path.Combine(new DirectoryInfo(Environment.SystemDirectory).Root.FullName.ToString(), "temp"); //win10无读取temp目录的权限////

                System.Reflection.Assembly assembly = Assembly.GetExecutingAssembly();
                foreach (String eachEmbedResourceName in assembly.GetManifestResourceNames())
                {
                    if (eachEmbedResourceName.Contains(embedResourcePath + "." + embedResourceCategoryPath) &&
                        eachEmbedResourceName.Contains(dllModuleName + "." + "dll"))
                    {
                        targetFileName = eachEmbedResourceName.Substring(eachEmbedResourceName.LastIndexOf($"{embedResourcePath}.{embedResourceCategoryPath}") + $"{embedResourcePath}.{embedResourceCategoryPath}.".Length);
                        System.IO.Stream embedResoutceStream = assembly.GetManifestResourceStream(eachEmbedResourceName);
                        if (eachEmbedResourceName.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase))
                        {
                            targetPath = Path.Combine(tempPath, targetFileName);
                        }
                        byte[] buffer = new byte[embedResoutceStream.Length];
                        embedResoutceStream.Read(buffer, 0, buffer.Length);     //将流的内容读到缓冲区

                        FileStream fs = new FileStream(targetPath, FileMode.Create, FileAccess.Write);
                        fs.Write(buffer, 0, buffer.Length);
                        fs.Flush();
                        fs.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            #endregion

            #region  择文件
            if (String.IsNullOrEmpty(targetPath))
            {
                //  We'll need a path to the assembly to install.
                var            dllFullPath    = @"";
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.InitialDirectory = Application.StartupPath;
                openFileDialog.Filter           = "所有文件|*.*|Dll文件(*.Dll)|*.Dll";
                openFileDialog.FilterIndex      = 7;
                openFileDialog.RestoreDirectory = true;
                openFileDialog.Title            = "打开Dll文件";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(openFileDialog.FileName))
                    {
                        targetPath = openFileDialog.FileName;
                    }
                }
            }
            #endregion

            #region 注册
            if (!String.IsNullOrEmpty(targetPath) && File.Exists(targetPath))
            {
                if (log)
                {
                    //  Install the assembly, without an install reference.
                    AssemblyCache.InstallAssembly(targetPath, null, AssemblyCommitFlags.Default);
                    string message = "The assembly was installed successfully!";
                }
            }
            #endregion

            #region  除文件
            if (!String.IsNullOrEmpty(targetPath) && File.Exists(targetPath))
            {
                while (File.Exists(targetPath))
                {
                    File.Delete(targetPath);
                    Thread.Sleep(1000);
                }
            }
            #endregion
        }
Пример #44
-1
        static Assembly ResolveFromResources(Assembly container, string name)
        {
            string[] allNames = container.GetManifestResourceNames();

            string
                fileName = name + ".dll",
                fullName = Array.Find(allNames, e => e.EndsWith(fileName, StringComparison.Ordinal)),

                pdbName = Path.ChangeExtension(fileName, ".pdb"),
                fullPdbName = Array.Find(allNames, e => e.EndsWith(pdbName, StringComparison.Ordinal)); // null if not found

            if (String.IsNullOrEmpty(fullName))
                return null;

            using (Stream dllStream = container.GetManifestResourceStream(fullName))
            {
                byte[] assembly = new byte[dllStream.Length];
                dllStream.Read(assembly, 0, assembly.Length);

                // load PDB if exists
                if (!String.IsNullOrEmpty(fullPdbName))
                    using (Stream pdbStream = container.GetManifestResourceStream(fullPdbName))
                    {
                        byte[] pdb = new byte[pdbStream.Length];
                        pdbStream.Read(pdb, 0, pdb.Length);

                        return Assembly.Load(assembly, pdb);
                    }

                return Assembly.Load(assembly);
            }
        }