public static void SaveRess(Dictionary <string, string[]> ResXData, string FsPath) { System.Resources.ResXResourceWriter test = new System.Resources.ResXResourceWriter(FsPath); try { foreach (KeyValuePair <string, string[]> item in ResXData) { test.AddResource(new System.Resources.ResXDataNode(item.Key.ToString(), item.Value)); } } catch (Exception Ex) { if (!VarGlobal.LessVerbose) { Console.WriteLine("{0}{1}{1}{2}", Ex.Message, Environment.NewLine, Ex.StackTrace); } } try { if (null != test) { test.Close(); } } catch (Exception Ex) { if (!VarGlobal.LessVerbose) { Console.WriteLine("{0}{1}{1}{2}", Ex.Message, Environment.NewLine, Ex.StackTrace); } } }
public void WriteLanguageToStream(string language, Stream stream) { using (var w = new System.Resources.ResXResourceWriter(stream)) { foreach (var pair in stringStorage[language]) { w.AddResource(pair.Key, pair.Value); } } }
private static string CreateDummyResourceFile() { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.StreamWriter sw = new System.IO.StreamWriter(ms, new System.Text.UTF8Encoding(false)); System.Resources.ResXResourceWriter writer = new System.Resources.ResXResourceWriter(sw); writer.AddResource("MyLittleResource", "MyLittleResourceValue"); writer.Generate(); ms.Flush(); ms.Seek(0, System.IO.SeekOrigin.Begin); return(System.Text.Encoding.UTF8.GetString(ms.ToArray())); }
/// <summary> /// Loads an Icon Error Checked. /// </summary> internal static System.Drawing.Icon _LoadIconErrorChecked(string resource, int Width, int Height) { int error = 0; System.Drawing.Icon retIcon = null; System.IntPtr hIcon = System.IntPtr.Zero; System.Reflection.Module hMod = null; try { hMod = System.Reflection.Assembly.GetEntryAssembly().GetModules()[0]; } catch (System.Exception) { } if (hMod != null) { System.IntPtr hProc = System.Runtime.InteropServices.Marshal.GetHINSTANCE(hMod); hIcon = LoadImage(hProc, resource, (uint)Enums.LoadImageTypes.IMAGE_ICON, Width, Height, (uint)Enums.LoadImagefuLoad.LR_SHARED); error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (error == 0 && hIcon != System.IntPtr.Zero) { System.Drawing.Icon iconold = System.Drawing.Icon.FromHandle(hIcon); retIcon = new System.Drawing.Icon(iconold, Width, Height); } } else { // Forms Designer hack. // Load from a *.resx if it exists, otherwise make one. if (!System.IO.File.Exists(ResourcesDir.resourcespath)) { System.Resources.ResXResourceWriter resx = new System.Resources.ResXResourceWriter(ResourcesDir.resourcespath); System.IO.MemoryStream iconstream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(ResourcesDir.iconpath)); System.Drawing.Icon icon2Dump = new System.Drawing.Icon(iconstream); resx.AddResource(GetFileBaseName(ResourcesDir.iconpath).Trim(".ico".ToCharArray()), icon2Dump); icon2Dump.Dispose(); // write resource file. resx.Dispose(); } // now read it. System.Resources.ResXResourceSet resxSet = new System.Resources.ResXResourceSet(ResourcesDir.resourcespath); // hopefully this works. System.Drawing.Icon iconold = (System.Drawing.Icon)resxSet.GetObject(GetFileBaseName(ResourcesDir.iconpath).Trim(".ico".ToCharArray())); retIcon = new System.Drawing.Icon(iconold, Width, Height); hIcon = retIcon.Handle; resxSet.Dispose(); } if (hIcon == System.IntPtr.Zero) { MessageManager.ShowError("LoadImage returned Error Code: " + error + ".", "Error!"); } return(retIcon); }
private void SystemSerializeObjects(object[] referenceObjects, Func <Type, string> typeNameConverter = null, ITypeResolutionService typeResolver = null) { #if !NETCOREAPP2_0 using (new TestExecutionContext.IsolatedContext()) { Console.WriteLine($"------------------System ResXResourceWriter (Items Count: {referenceObjects.Length})--------------------"); try { StringBuilder sb = new StringBuilder(); using (SystemResXResourceWriter writer = #if NET35 || NETCOREAPP3_0 new SystemResXResourceWriter(new StringWriter(sb)) #else new SystemResXResourceWriter(new StringWriter(sb), typeNameConverter) #endif ) { int i = 0; foreach (object item in referenceObjects) { writer.AddResource(i++ + "_" + (item == null ? "null" : item.GetType().Name), item); } } Console.WriteLine(sb.ToString()); List <object> deserializedObjects = new List <object>(); using (SystemResXResourceReader reader = SystemResXResourceReader.FromFileContents(sb.ToString(), typeResolver)) { foreach (DictionaryEntry item in reader) { deserializedObjects.Add(item.Value); } } AssertItemsEqual(referenceObjects, deserializedObjects.ToArray()); } catch (Exception e) { Console.WriteLine($"System serialization failed: {e}"); } } #endif }
static int Main(string[] args) { if (args.Length == 0) { MessageBox.Show("错误:没有打包资源参数...请拖拽需要打包的文件到本exe上"); return(2); } // 生成的资源包文件路径 string output_file = "FKResourcePack.resx"; output_file = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), output_file); // 逐个打到资源包里 System.Resources.ResXResourceWriter rsxw = new System.Resources.ResXResourceWriter(output_file); for (int i = 0; i < args.Length; i++) { string strSourceResFile = args[i]; if (File.Exists(strSourceResFile)) { FileStream fs = File.OpenRead(strSourceResFile); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); rsxw.AddResource(Path.GetFileName(strSourceResFile), data); } else { MessageBox.Show(string.Format("错误:需要打包的资源文件 \"{0}\" 不存在...", strSourceResFile)); return(1); } } rsxw.Generate(); rsxw.Close(); MessageBox.Show(string.Format("打包完成,资源包目录为: \"{0}\"", output_file)); return(0); }
private static void CreateResourceFile(string inputFile, string outputFile) { string fileName = Path.GetFileName(inputFile); System.Resources.IResourceWriter writer = null; FileStream fs = null; BinaryReader br = null; try { //writer = new System.Resources.ResourceWriter(outputFile); writer = new System.Resources.ResXResourceWriter(outputFile); fs = new FileStream(inputFile, FileMode.Open); br = new BinaryReader(fs); byte[] myBuffer = new byte[br.BaseStream.Length]; for (long i = 0; i < br.BaseStream.Length; i++) { myBuffer[i] = br.ReadByte(); } writer.AddResource(fileName, myBuffer); writer.Generate(); //writer.Close(); } finally { if (writer != null) { writer.Close(); } if (fs != null) { fs.Close(); } if (br != null) { br.Close(); } } }
/* * public bool IsExistRegValue(string path, string keyvalue) * { * string[] subkeyNames; * RegistryKey hkml = Registry.LocalMachine; * RegistryKey software = hkml.OpenSubKey(path); * //RegistryKey software = hkml.OpenSubKey("SOFTWARE\\test", true); * subkeyNames = software.GetValueNames(); * //取得该项下所有键值的名称的序列,并传递给预定的数组中 * foreach (string keyName in subkeyNames) * { * if (keyName == keyvalue) //判断键值的名称 * { * hkml.Close(); * return true; * } * * } * hkml.Close(); * return false; * } */ #endregion public void ChangePW() { if (OldPwBox.Password == "" || NewPwBox.Password == "") { MessageBox.Show("密码不能为空!"); return; } else if (OldPwBox.Password != pword) { MessageBox.Show("原密码错误!"); return; } else { pword = NewPwBox.Password; System.Resources.ResXResourceWriter rw = new System.Resources.ResXResourceWriter(respath); rw.AddResource("PASSWORD", pword); rw.Close(); MessageBox.Show("修改成功!"); WinChange(2); } }
static int Main(string[] args) { if (args.Length == 0) { System.Console.WriteLine("Error: no arguments."); return(2); } string output_file = "driver.resx"; output_file = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), output_file); System.Resources.ResXResourceWriter rsxw = new System.Resources.ResXResourceWriter(output_file); for (int i = 0; i < args.Length; i++) { string driver_file = args[i]; if (File.Exists(driver_file)) { FileStream fs = File.OpenRead(driver_file); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); rsxw.AddResource(Path.GetFileName(driver_file), data); } else { System.Console.WriteLine("Error: file \"{0}\" not found.", driver_file); return(1); } } rsxw.Generate(); rsxw.Close(); return(0); }
static int Main(string[] args) { if (args.Length == 0) { System.Console.WriteLine("Error: no arguments."); return 2; } string output_file = "driver.resx"; output_file = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), output_file); System.Resources.ResXResourceWriter rsxw = new System.Resources.ResXResourceWriter(output_file); for (int i = 0; i < args.Length; i++) { string driver_file = args[i]; if (File.Exists(driver_file)) { FileStream fs = File.OpenRead(driver_file); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); rsxw.AddResource(Path.GetFileName(driver_file), data); } else { System.Console.WriteLine("Error: file \"{0}\" not found.", driver_file); return 1; } } rsxw.Generate(); rsxw.Close(); return 0; }
public void WriteLanguageToStream(string language, Stream stream) { using (var w = new System.Resources.ResXResourceWriter(stream)) { foreach (var pair in stringStorage[language]) w.AddResource(pair.Key, pair.Value); } }
/// <summary> /// Reads the binary data of the image and returns it as a formatted Base64 string /// which then can be used in a .resx file. /// It seems for bitmaps for buttons and toolbars and menuitems, we need gif bitmaps /// but for window icons we need ico files /// </summary> /// <param name="AImageFileName">Full file name of the image</param> /// <param name="AImageOrIcon">is this an icon or bitmap</param> /// <returns>the formatted Base64 representation of the image</returns> private string Image2Base64(string AImageFileName, string AImageOrIcon) { if (!File.Exists(AImageFileName)) { return ""; } // AlanP added this retry loop after getting fed up with generating the solution and finding that // access to go.gif.resx is denied. The assumption is that multi-threaded code generation // wants to access a well-used image file in multiple places. The resx file is only a temporary // file. A few lines down we delete it, which is probably why it fails to open. // If that is not the cause the code shouldn't do any harm. int nTries = 0; int nTriesLimit = 4; // 4 tries over 2 seconds should be enough! string exceptionMsg = String.Empty; TXMLParser parser = null; while (nTries < nTriesLimit) { try { System.Resources.ResXResourceWriter w = new System.Resources.ResXResourceWriter(AImageFileName + ".resx"); if (AImageOrIcon == "Icon") { w.AddResource(AImageFileName, new Icon(AImageFileName)); } else if ((AImageOrIcon == "Bitmap") && (Path.GetExtension(AImageFileName) == ".ico")) { w.AddResource(AImageFileName, (new Icon(AImageFileName)).ToBitmap()); } else { w.AddResource(AImageFileName, new Bitmap(AImageFileName)); } w.Close(); parser = new TXMLParser(AImageFileName + ".resx", false); File.Delete(AImageFileName + ".resx"); nTries = 999; // success! } catch (Exception ex) // probably an IO exception { nTries++; parser = null; exceptionMsg = ex.Message; Application.DoEvents(); System.Threading.Thread.Sleep(500); } } if ((nTries == nTriesLimit) || (parser == null)) { throw new IOException(String.Format( "The system had {0} attempts to create, parse and delete the file {1}.resx as a resource but the following IO exception was raised: {2}", nTries, AImageFileName, exceptionMsg)); } XmlDocument doc = parser.GetDocument(); XmlNode child = doc.DocumentElement.FirstChild; while (child != null) { if ((child.Name == "data") && (TYml2Xml.GetAttribute(child, "name") == AImageFileName)) { return child.InnerText; } child = child.NextSibling; } return string.Empty; }
private void generateResourceMenuItem_Click(object sender, EventArgs e) { Point origStart = GetOriginalXY(selStartMousePos); Point origEnd = GetOriginalXY(selEndMousePos); if (selStartMousePos.X != 0 || selStartMousePos.Y != 0) { int top = origStart.Y < origEnd.Y ? origStart.Y : origEnd.Y; int left = origStart.X < origEnd.X ? origStart.X : origEnd.X; int width = Math.Abs(origEnd.X - origStart.X); int height = Math.Abs(origEnd.Y - origStart.Y); Rectangle box = new Rectangle(left, top, width, height); Bitmap bitmap = ((Bitmap)image).Clone(box, ((Bitmap)image).PixelFormat); if (Statics.DTE.Solution.IsOpen) { foreach (EnvDTE.Project proj in Statics.DTE.Solution.Projects) { if (proj.Name.Contains("Test")) { try { ImageInputForm inputForm = new ImageInputForm(); inputForm.ShowDialog(); Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); string resFile = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.resx"; string resDesginFile = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.Designer.cs"; System.Resources.ResXResourceReader reader = new System.Resources.ResXResourceReader(resFile); using (System.Resources.ResXResourceWriter writer = new System.Resources.ResXResourceWriter(resFile + ".new")) { System.Collections.IDictionaryEnumerator iterator = reader.GetEnumerator(); while (iterator.MoveNext()) { writer.AddResource(iterator.Key.ToString(), iterator.Value); } writer.AddResource(inputForm.Input, bitmap); writer.Generate(); } File.Copy(resFile + ".new", resFile, true); File.Delete(resFile + ".new"); string[] unMatched; System.CodeDom.CodeCompileUnit unit = System.Resources.Tools.StronglyTypedResourceBuilder.Create(resFile, "Resources", proj.Properties.Item("DefaultNamespace").Value + ".Properties", codeProvider, true, out unMatched); using (StreamWriter designWriter = new StreamWriter(resDesginFile)) { codeProvider.GenerateCodeFromCompileUnit(unit, designWriter, new System.CodeDom.Compiler.CodeGeneratorOptions()); } MessageBox.Show("Image generation succeeded", "Resources Updated"); return; } catch (Exception ex) { MessageBox.Show("Image generation failed\n" + ex.Message, "Resources Did Not Update"); } } } MessageBox.Show("You need to have a project open, named *Test*", "Resources Did Not Update"); return; } MessageBox.Show("You need to have a solution open with a project named *Test*", "Resources Did Not Update"); return; } }
public void WriteResource(System.Resources.ResXResourceWriter writer) { writer.AddResource(resourceName, getResource()); }
private void CreateResourceFromImage(bool entire) { Bitmap bitmap = null; if (entire) { bitmap = (Bitmap)(zoomPanControl.ZoomPanImage.Clone()); } else if (HasImageSelection && !entire) { bitmap = ((Bitmap)zoomPanControl.ZoomPanImage).Clone(partBox, ((Bitmap)zoomPanControl.ZoomPanImage).PixelFormat); } if (bitmap != null) { if (Statics.DTE.Solution.IsOpen) { foreach (EnvDTE.Project proj in Statics.DTE.Solution.Projects) { if (proj.Name.Contains("Test")) { try { string resFile, resDesignFile, resNameSpace; System.CodeDom.Compiler.CodeDomProvider provider; if (proj.FileName.EndsWith("vbproj")) { resFile = Path.GetDirectoryName(proj.FileName) + @"\My Project\Resources.resx"; resDesignFile = Path.GetDirectoryName(proj.FileName) + @"\My Project\Resources.Designer.vb"; vbNS = resNameSpace = proj.Properties.Item("RootNamespace").Value.ToString(); provider = new Microsoft.VisualBasic.VBCodeProvider(); } else { resFile = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.resx"; resDesignFile = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.Designer.cs"; resNameSpace = proj.Properties.Item("DefaultNamespace").Value + ".Properties"; provider = new Microsoft.CSharp.CSharpCodeProvider(); } ImageInputForm inputForm = new ImageInputForm(); inputForm.ShowDialog(); System.Resources.ResXResourceReader reader = new System.Resources.ResXResourceReader(resFile); using (System.Resources.ResXResourceWriter writer = new System.Resources.ResXResourceWriter(resFile + ".new")) { System.Collections.IDictionaryEnumerator iterator = reader.GetEnumerator(); while (iterator.MoveNext()) { writer.AddResource(iterator.Key.ToString(), iterator.Value); } writer.AddResource(inputForm.Input, bitmap); writer.Generate(); } File.Copy(resFile + ".new", resFile, true); File.Delete(resFile + ".new"); string[] unMatched; System.CodeDom.CodeCompileUnit unit = System.Resources.Tools.StronglyTypedResourceBuilder.Create(resFile, "Resources", resNameSpace, provider, true, out unMatched); using (StreamWriter designWriter = new StreamWriter(resDesignFile)) { provider.GenerateCodeFromCompileUnit(unit, designWriter, new System.CodeDom.Compiler.CodeGeneratorOptions()); } MessageBox.Show("Image generation succeeded", "Resources Updated"); if (entire) { entireResName = inputForm.Input; NotifyPropertyChanged("EntireResName"); } else { partResName = inputForm.Input; NotifyPropertyChanged("PartialResName"); } return; } catch (Exception ex) { MessageBox.Show("Image generation failed\n" + ex.Message, "Resources Did Not Update"); return; } } } MessageBox.Show("You need to have a project open, named *Test*", "Resources Did Not Update"); return; } MessageBox.Show("You need to have a solution open with a project named *Test*", "Resources Did Not Update"); return; } }