public static void UpdateResourceFile(Hashtable data, string path, TranslatorForm form) { form.TextOutput = "Writing " + path + "..."; Hashtable resourceEntries = new Hashtable(); bool check = false; //Get existing resources ResXResourceReader reader = new ResXResourceReader(path); if (reader != null) { IDictionaryEnumerator id = reader.GetEnumerator(); foreach (DictionaryEntry d in reader) { if (d.Value == null) resourceEntries.Add(d.Key.ToString(), ""); else resourceEntries.Add(d.Key.ToString(), d.Value.ToString()); } reader.Close(); } //Modify resources here... foreach (String key in data.Keys) { if (!resourceEntries.ContainsKey(key)) { String value = data[key].ToString(); if (value == null) value = ""; resourceEntries.Add(key, value); } } //Write the combined resource file ResXResourceWriter resourceWriter = new ResXResourceWriter(path); foreach (String key in resourceEntries.Keys) { resourceWriter.AddResource(key, resourceEntries[key]); } resourceWriter.Generate(); resourceWriter.Close(); //Check if entered correctly reader = new ResXResourceReader(path); if (reader != null) { foreach (DictionaryEntry d in reader) foreach (String key in resourceEntries.Keys) { if ((string) d.Key == key && (string) d.Value == (string) resourceEntries[key]) check = true; } reader.Close(); } if (check) form.TextOutput = path + " written successfully"; else form.TextOutput = path + " not written !!"; }
public void Test () { Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo ("de-DE"); ResXResourceWriter w = new ResXResourceWriter (fileName); w.AddResource ("point", new Point (42, 43)); w.Generate (); w.Close (); int count = 0; ResXResourceReader r = new ResXResourceReader (fileName); IDictionaryEnumerator e = r.GetEnumerator (); while (e.MoveNext ()) { if ((string) e.Key == "point") { Assert.AreEqual (typeof (Point), e.Value.GetType (), "#1"); Point p = (Point) e.Value; Assert.AreEqual (42, p.X, "#2"); Assert.AreEqual (43, p.Y, "#3"); count++; } } r.Close (); Assert.AreEqual (1, count, "#100"); }
public static void generateResourceFile(string sourceDirectory, string targetResrouceFile) { IEnumerable<string> files = Directory.EnumerateFiles(sourceDirectory,"*.*",SearchOption.AllDirectories); ResXResourceWriter rw=new ResXResourceWriter(targetResrouceFile); string baseUI = ""; string baseCOM = ""; StringBuilder allACE = new StringBuilder(); StringBuilder allJS = new StringBuilder(); StringBuilder allCom = new StringBuilder(); StringBuilder allUI = new StringBuilder(); StringBuilder allCSS = new StringBuilder(); StringBuilder jquery = new StringBuilder(); string jq_timePicker = ""; foreach(string file in files){ if(!file.Contains(".svn")){/* don't include subversion files */ /* only include certain files. Other files don't get included */ if(file.EndsWith(".png")||file.EndsWith(".jpg") ||file.EndsWith(".gif")||file.EndsWith(".ico")) { rw.AddResource(getRscString(file,sourceDirectory),File.ReadAllBytes(file)); }else if(file.EndsWith(".js")||file.EndsWith(".html")|| file.EndsWith(".css")||file.EndsWith(".aspx")||file.EndsWith(".sql") ||file.EndsWith(".txt")) { string content = File.ReadAllText(file); if(file.EndsWith(".css")){ allCSS.Append(content+Environment.NewLine); } else if(file.EndsWith(".js")) { if(file.ToLower().Contains("ui\\ui.js")){ baseUI = content+Environment.NewLine+Environment.NewLine; } else if(file.ToLower().Contains("commerce\\commerce.js")) { baseCOM = content+Environment.NewLine+Environment.NewLine; } else if(file.ToLower().Contains("timepicker\\jquery-timepicker.js")) { jq_timePicker = content + Environment.NewLine + Environment.NewLine; } else if(file.ToLower().Contains("jquery\\jquery")) { jquery.Append(content+Environment.NewLine+Environment.NewLine); } else if(file.ToLower().Contains("ui\\")){ allUI.Append(content+Environment.NewLine+Environment.NewLine); allJS.Append(content+Environment.NewLine+Environment.NewLine); } else if(file.ToLower().Contains("ace\\")){ allACE.Append(content+Environment.NewLine+Environment.NewLine); } else if(file.ToLower().Contains("commerce\\")){ allCom.Append(content+Environment.NewLine+Environment.NewLine); allJS.Append(content+Environment.NewLine+Environment.NewLine); }else{ allJS.Append(content+Environment.NewLine+Environment.NewLine); } } rw.AddResource(getRscString(file,sourceDirectory),content); } else if(file.ToLower() == "thumbs.db") { File.Delete(file); /* evil */ } } } rw.AddResource("admin__renditionjs", baseUI + baseCOM + allJS.ToString()); rw.AddResource("admin__acejs", allACE.ToString()); rw.AddResource("admin__jqueryjs", jquery.ToString()); rw.AddResource("admin__renditionUIjs", allACE.ToString() + baseUI + allUI.ToString()); rw.Generate(); rw.Close(); }
public static void CreateResourceFile(String path) { var pathString = Path.GetDirectoryName(path); if (!Directory.Exists(pathString)) System.IO.Directory.CreateDirectory(pathString); ResXResourceWriter resourceWriter = new ResXResourceWriter(path); resourceWriter.Generate(); resourceWriter.Close(); }
private void btnSave_Click(object sender, EventArgs e) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = "Save resource file"; dlg.Filter = "Resource File|*.resx"; dlg.FileName = cbDestLang.SelectedValue.ToString() + ".resx"; if (dlg.ShowDialog() != DialogResult.OK) return; ResXResourceWriter rsxw = new ResXResourceWriter(dlg.FileName); var table = (DataTable) grid.DataSource; foreach( DataRow row in table.Rows ) { rsxw.AddResource( row[0].ToString(), row[2].ToString()); } rsxw.Generate(); rsxw.Close(); }
public void GivenThereIsAResxFileWhichFullPathIsHasTheseContents(string p0, Table table) { using (var fileStream = File.Create(Path.Combine(_testFolder, p0))) { using (var resxWriter = new ResXResourceWriter(fileStream)) { foreach (var row in table.Rows) { resxWriter.AddResource(row["Name"], row["Value"]); } resxWriter.Generate(); resxWriter.Close(); } fileStream.Close(); } }
public static void UpdateResourceFile(Hashtable data, String path) { Hashtable resourceEntries = new Hashtable(); //Add all changes... foreach (String key in data.Keys) { String value = data[key].ToString(); if (value == null) value = ""; resourceEntries.Add(key, value); } //Get existing resources ResXResourceReader reader = new ResXResourceReader(path); if (reader != null) { IDictionaryEnumerator id = reader.GetEnumerator(); foreach (DictionaryEntry d in reader) { if (!resourceEntries.ContainsKey(d.Key.ToString())) { if (d.Value == null) resourceEntries.Add(d.Key.ToString(), ""); else resourceEntries.Add(d.Key.ToString(), d.Value.ToString()); } } reader.Close(); } //Write the combined resource file ResXResourceWriter resourceWriter = new ResXResourceWriter(path); foreach (String key in resourceEntries.Keys) { resourceWriter.AddResource(key, resourceEntries[key]); } resourceWriter.Generate(); resourceWriter.Close(); }
public static void Main() { System.Resources.ResXResourceWriter resourceWriter = new ResXResourceWriter("Content.resx"); FileStream contentFile; StreamReader fileReader; contentFile = new System.IO.FileStream("ResourceHeader.txt", FileMode.Open, FileAccess.Read, FileShare.Read); fileReader = new StreamReader(contentFile); resourceWriter.AddResource("ResourceHeader", fileReader.ReadToEnd()); contentFile = new System.IO.FileStream("gplexx.frame", FileMode.Open, FileAccess.Read, FileShare.Read); fileReader = new StreamReader(contentFile); resourceWriter.AddResource("GplexxFrame", fileReader.ReadToEnd()); contentFile = new System.IO.FileStream("GplexBuffers.txt", FileMode.Open, FileAccess.Read, FileShare.Read); fileReader = new StreamReader(contentFile); resourceWriter.AddResource("GplexBuffers", fileReader.ReadToEnd()); resourceWriter.Generate(); resourceWriter.Close(); }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: ResTool <assembly> <resxfile>"); Environment.Exit(64); } Assembly asy = Assembly.LoadFrom(args[0]); ResXResourceWriter resx = new ResXResourceWriter(args[1]); foreach (Type t in asy.GetTypes()) { foreach (FieldInfo fi in t.GetFields()) { if (!fi.IsStatic) continue; string n = t.Name + "." + fi.Name; Console.WriteLine(n); resx.AddResource(n, fi.GetValue(null)); } } resx.Close(); }
private void TranslateFile(string filename, string locale, string newDir) { string shortName = Path.GetFileName(filename); string nameWithoutExt = Path.GetFileNameWithoutExtension(filename); string newname = nameWithoutExt + "." + locale + ".resx"; newname = newDir + "\\" + newname; //if file already exists bool fileExists = File.Exists(newname); Dictionary<string, string> existing = new Dictionary<string, string>(); if (fileExists) { Console.WriteLine("File " + newname + " already exists. Existing resources in it will be preserved."); //get existing keys list ResXResourceReader readerNewFile = new ResXResourceReader(newname); foreach (DictionaryEntry d in readerNewFile) existing.Add(d.Key.ToString(), d.Value.ToString()); readerNewFile.Close(); } else { Console.WriteLine("Creating file " + newname); } Console.WriteLine("Translating file " + shortName + " to " + locale + "...."); Application.DoEvents(); //I know its bad but can't go multithreading, since I have to update UI ResXResourceReader reader = new ResXResourceReader(filename); ResXResourceWriter writer = new ResXResourceWriter(newname); foreach (DictionaryEntry d in reader) { //leave existing text intact (if its not empty) if (fileExists && existing.Keys.Contains(d.Key.ToString()) && !string.IsNullOrEmpty(existing[d.Key.ToString()])) { writer.AddResource(d.Key.ToString(), existing[d.Key.ToString()]); } else { string originalString = d.Value.ToString(); if (!string.IsNullOrEmpty(originalString.Trim())) { string langPair = "hu|" + LanguageNamesList[locale]; //string translatedString = GoogleTranslate.TranslateText(originalString, langPair); string translatedString = GoogleTranslate.TranslateGoogle(originalString, "hu", LanguageNamesList[locale]); Console.WriteLine("[" + originalString + " -> " + translatedString + "]"); writer.AddResource(d.Key.ToString(), translatedString); //Thread.Sleep(100); //to prevent spam detector at google } } } writer.Close(); reader.Close(); }
void WriteResourceFile( ) { ResXResourceWriter rxrw = new ResXResourceWriter( fullFileName ); foreach ( IResource res_abstract in resourceList.Items ) { switch ( res_abstract.ResourceType ) { case ResourceType.TypeImage: ResourceImage resImage = res_abstract as ResourceImage; if ( resImage.Image == null ) continue; rxrw.AddResource( resImage.ResourceName, resImage.Image ); break; case ResourceType.TypeString: ResourceString resStr = res_abstract as ResourceString; if ( resStr == null ) continue; rxrw.AddResource( resStr.ResourceName, resStr.Text ); break; case ResourceType.TypeCursor: ResourceCursor resCursor = res_abstract as ResourceCursor; if ( resCursor == null ) continue; rxrw.AddResource( resCursor.ResourceName, resCursor.Cursor ); break; case ResourceType.TypeIcon: ResourceIcon resIcon = res_abstract as ResourceIcon; if ( resIcon == null ) continue; rxrw.AddResource( resIcon.ResourceName, resIcon.Icon ); break; case ResourceType.TypeColor: ResourceColor resColor = res_abstract as ResourceColor; if ( resColor == null ) continue; rxrw.AddResource( resColor.ResourceName, resColor.Color ); break; case ResourceType.TypeByteArray: ResourceByteArray resByteArray = res_abstract as ResourceByteArray; if ( resByteArray == null ) continue; rxrw.AddResource( resByteArray.ResourceName, resByteArray.ByteArray ); break; default: break; } } rxrw.Close( ); }
static void Main(string[] args) { Console.WriteLine("Psuedoizer: Adapted from MSDN BugSlayer 2004-Apr i18n Article."); if(args.Length < 2) { Console.WriteLine("Purpose: Takes an English resource file (resx) and creates an artificial"); Console.WriteLine(" but still readable Euro-like language to exercise your i18n code"); Console.WriteLine(" without a formal translation."); Console.WriteLine(String.Empty); Console.WriteLine("Psuedoizer.exe infile outfile [/b]"); Console.WriteLine(" Example:"); Console.WriteLine(" Psuedoizer.exe strings.en.resx strings.ja-JP.resx"); Console.WriteLine(" /b - Include blank resources"); System.Environment.Exit(1); } string fileName = args[0]; string fileSaveName = args[1]; bool IncludeBlankResources = (args.Length >= 3 && args[2] == "/b"); // Open the input file. ResXResourceReader reader = new ResXResourceReader ( fileName ) ; try { // Get the enumerator. If this throws an ArguementException // it means the file is not a .RESX file. IDictionaryEnumerator enumerator = reader.GetEnumerator ( ) ; // Allocate the list for this instance. SortedList textResourcesList = new SortedList ( ) ; // Run through the file looking for only true text related // properties and only those with values set. foreach ( DictionaryEntry dic in reader ) { // Only consider this entry if the value is something. if ( null != dic.Value ) { // Is this a System.String. if ( "System.String" == dic.Value.GetType().ToString()) { String KeyString = dic.Key.ToString ( ) ; // Make sure the key name does not start with the // "$" or ">>" meta characters and is not an empty // string (or we're explicitly including empty strings). if ( ( false == KeyString.StartsWith ( ">>" ) ) && ( false == KeyString.StartsWith ( "$" ) ) && ( IncludeBlankResources || "" != dic.Value.ToString() ) ) { // We've got a winner. textResourcesList.Add ( dic.Key , dic.Value ) ; } // Special case the Windows Form "$this.Text" or // I don't get the form titles. if ( 0 == String.Compare ( KeyString,"$this.Text")) { textResourcesList.Add ( dic.Key , dic.Value ) ; } } } } // It's entirely possible that there are no text strings in the // .ResX file. if ( textResourcesList.Count > 0 ) { if ( null != fileSaveName ) { // Create the new file. ResXResourceWriter writer = new ResXResourceWriter ( fileSaveName ) ; foreach ( DictionaryEntry textdic in textResourcesList ) { writer.AddResource ( textdic.Key.ToString(), Psuedoizer.ConvertToFakeInternationalized(textdic.Value.ToString())); } writer.Generate ( ) ; writer.Close ( ) ; Console.WriteLine("Converted " + textResourcesList.Count + " text resource(s)."); } } else { Console.Write("WARNING: No text resources found in " + fileName); System.Environment.Exit(2); } } catch(Exception e) { Console.Write(e.ToString()); System.Environment.Exit(1); } }
// Write any localized strings to the localized file public void Write() { // Create the new file. ResXResourceWriter writer = new ResXResourceWriter(LocalizedFileName); // Iterate the list view and write current items. foreach (LocString locstr in AllStrings) { if (!string.IsNullOrEmpty(locstr.Localized)) writer.AddResource(locstr.Name, locstr.Localized); } // Write all the non-string nodes back to the file. foreach (ResXDataNode dataNode in nonStringNodes) writer.AddResource(dataNode); writer.Generate(); writer.Close(); }
private void saveResxFiles(bool askUnsaved) { try { if (askUnsaved) { if (!unsavedChanges) return; if (DialogResult.No == MessageBox.Show(this, LangHandler.GetString("txtSave1"), LangHandler.GetString("txtSave2"), MessageBoxButtons.YesNo, MessageBoxIcon.Question)) return; } txtComment_Leave(null, EventArgs.Empty); txtValue_Leave(null, EventArgs.Empty); if (SettingsHandler.Instance.SortByKeyOnSave && dataGridView.Columns.Contains("keys")) dataGridView.Sort(dataGridView.Columns["keys"], ListSortDirection.Ascending); for (int column = 1; column < dataGridView.Columns.Count; column++) { using (ResXResourceWriter resourceWriter = new ResXResourceWriter(dataGridView.Columns[column].Name)) { for (int row = 0; row < dataGridView.Rows.Count; row++) { ResXDataNode currentNode = dataGridView.Rows[row].Cells[column].Tag as ResXDataNode; Object currentValue = dataGridView.Rows[row].Cells[column].Value as Object; bool isReadOnly = dataGridView.Rows[row].Cells[column].ReadOnly; if (currentValue != null && !isReadOnly) { ResXDataNode nodeToAdd = new ResXDataNode((string)dataGridView.Rows[row].Cells["keys"].Value, currentValue); if (currentNode != null) nodeToAdd.Comment = currentNode.Comment; resourceWriter.AddResource(nodeToAdd); continue; } if (currentNode != null && isReadOnly) { resourceWriter.AddResource(currentNode); } } resourceWriter.Generate(); resourceWriter.Close(); } } unsavedChanges = false; resetColors(); } catch (Exception ex) { #if (DEBUG) MessageBox.Show(this, string.Format("{0}\n\n{1}", ex.Message, ex.StackTrace), LangHandler.GetString("errorSaving"), MessageBoxButtons.OK, MessageBoxIcon.Error); #else MessageBox.Show(this, ex.Message, LangHandler.GetString("errorSaving"), MessageBoxButtons.OK, MessageBoxIcon.Error); #endif } }
/// <summary> /// 从resource文件还原resx文件 /// </summary> /// <param name="strPath">文件路径</param> /// <param name="strCsProj">csproj内容</param> private void RestoreResXFromResource(string strPath, ref string strCsProj) { string[] files = Directory.GetFiles(strPath, "*.resources");//查询文件 for (int i = 0; i < (int)files.Length; i++) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(files[i].Substring(selectPath.Length)); //取文件名去掉扩展名 string strResxFile = Path.Combine(strPath, string.Concat(string.Join("\\", fileNameWithoutExtension.Split(new char[] { '.' })), ".resx")); //resx文件路径 ResourceReader resourceReaders = new ResourceReader(files[i]); //读取资源文件 ResXResourceWriter resXResourceWriter = new ResXResourceWriter(strResxFile); //打开resx文件 foreach (DictionaryEntry resourceReader in resourceReaders) {//从resource文件中读取资源写入resx文件 try { resXResourceWriter.AddResource(resourceReader.Key.ToString(), resourceReader.Value); } catch (Exception ex) { UpdateMsg(resourceReader.Key.ToString() + "\r\n" + ex.ToString()); } } resXResourceWriter.Close(); resourceReaders.Close(); UpdateMsg(strResxFile.Substring(selectPath.Length));//resx文件更新消息 if (strCsProj != null) {//更新csproj string strResXName = strResxFile.Substring(selectPath.Length); //resx文件名 if (!strCsProj.Contains(string.Concat("=\"", strResXName, "\""))) {//csproj中不包含则添加 int num = strCsProj.LastIndexOf("</ItemGroup>");//最后位置 if (num <= 0) {//适应低版本 num = strCsProj.LastIndexOf("=\"EmbeddedResource\""); strCsProj = string.Concat(strCsProj.Substring(0, num) , "=\"EmbeddedResource\" />\r\n\t\t<File RelPath=\"" , strResXName , "\" DependentUpon=\"" , Path.GetFileNameWithoutExtension(strResXName) ,".cs\" BuildAction" , strCsProj.Substring(num)); } else { strCsProj = string.Concat(strCsProj.Substring(0, num) , " <EmbeddedResource Include=\"" , strResXName , "\">\r\n\t<SubType>Designer</SubType>\r\n\t<DependentUpon>" , Path.GetFileNameWithoutExtension(strResXName) , ".cs</DependentUpon>\r\n\t</EmbeddedResource>" , strCsProj.Substring(num)); //插入resx文件引用 strCsProj = strCsProj.Replace(string.Concat("<EmbeddedResource Include=\"" , Path.GetFileName(files[i]) , "\" />") , "");//删除resources文件引用 } } } } }
/// <summary> /// 保存配置数据.如果加载失败,将抛异常 /// </summary> public void Save() { SecurityOpr secOpr = null; StringBuilder sb = null; StringWriter stringWriter = null; try { secOpr = new SecurityOpr(GlobalVar.Instanse.SecurityKey); sb = new StringBuilder(); stringWriter = new StringWriter(sb); m_Writer = new ResXResourceWriter(stringWriter); foreach (KeyValuePair<string, object> item in m_cfgDatas) m_Writer.AddResource(item.Key, item.Value); m_Writer.Generate();//将数据写入字符串流 //将数据进行加密写入文件 secOpr.WriteToFile(m_StrPath, sb.ToString()); } catch (Exception ex) { throw ex; } finally { if (m_Writer != null) m_Writer.Close(); if (stringWriter != null) stringWriter.Close(); } }
} catch(Exception e) { System.Console.Error.WriteLine("Got exception: {0} while testing {1}", e.Message, fileName); return false; } return true; } private void BrowseClick(object sender, System.EventArgs e) { if (sender == btnBrowseForResx) { if (SFDlg.ShowDialog() != DialogResult.Cancel) txtResxFile.Text = SFDlg.FileName; } else { if (OFDlg.ShowDialog() != DialogResult.Cancel) txtZipFile.Text = OFDlg.FileName; } } private void btnCancel_Click(object sender, System.EventArgs e) {
private void Save(string culture, string fullPath) { using (var fileStream = File.OpenWrite(fullPath)) { fileStream.SetLength(0); fileStream.Flush(); using (var resxWriter = new ResXResourceWriter(fileStream)) { foreach (var item in Dictionary) { var key = item.Key; if (!item.Value.ContainsKey(culture)) continue; var value = item.Value[culture]; // We should allow empty values. //if (string.IsNullOrEmpty(value)) continue; resxWriter.AddResource(key, value); } resxWriter.Generate(); resxWriter.Close(); } fileStream.Close(); } }
/// <summary> /// Export to resx files /// </summary> /// <param name="path">path to place resx files</param> public void ToResx(string path, Action<string> addSummaryDelegate) { var cultures = this.SecondaryTranslation.Select(rl => rl.Culture) .Distinct(); foreach (var culture in cultures) { string pathCulture = Path.Combine(path, culture); if (!System.IO.Directory.Exists(pathCulture)) { System.IO.Directory.CreateDirectory(pathCulture); } foreach (var resx in this.TranslationSource) { var fullPath = Path.Combine(pathCulture, resx.FileSource); var directoryName = Path.GetDirectoryName(fullPath); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath); var fileName = fileNameWithoutExtension + "." + culture + ".resx"; Directory.CreateDirectory(directoryName); ResXResourceWriter rw = new ResXResourceWriter(Path.Combine(directoryName, fileName)); foreach (var entry in this.SecondaryTranslation.Where(r => r.PrimaryTranslationRow.TranslationSource == resx.Id) .Where(r => r.Culture == culture) .Where(r => !string.IsNullOrEmpty(r.Value))) { var value = entry.Value; value = value.Replace("\\r", "\r"); value = value.Replace("\\n", "\n"); rw.AddResource(new ResXDataNode(entry.PrimaryTranslationRow.Key, value)); } rw.Close(); addSummaryDelegate("Wrote localized resx: " + fileName); } } }
public void WriteRead1 () { ResXResourceWriter rw = new ResXResourceWriter ("resx.resx"); serializable ser = new serializable ("aaaaa", "bbbbb"); ResXDataNode dn = new ResXDataNode ("test", ser); dn.Comment = "comment"; rw.AddResource (dn); rw.Close (); bool found = false; ResXResourceReader rr = new ResXResourceReader ("resx.resx"); rr.UseResXDataNodes = true; IDictionaryEnumerator en = rr.GetEnumerator (); while (en.MoveNext ()) { ResXDataNode node = ((DictionaryEntry)en.Current).Value as ResXDataNode; if (node == null) break; serializable o = node.GetValue ((AssemblyName []) null) as serializable; if (o != null) { found = true; Assert.AreEqual (ser, o, "#A1"); Assert.AreEqual ("comment", node.Comment, "#A3"); } } rr.Close (); Assert.IsTrue (found, "#A2 - Serialized object not found on resx"); }
/// <summary> /// Performs the Synchronization of the RESX files. /// </summary> /// <param name="backup">Specifies whether to backup the destination file before modifying it.</param> /// <param name="addOnly">Specifies whether to only add new keys, without removing deleted ones.</param> /// <param name="verbose">Specifies whether to print additional information.</param> /// <param name="added">The number of added keys.</param> /// <param name="removed">The number of removed keys.</param> public void SyncronizeResources(bool backup, bool addOnly, bool verbose, out int added, out int removed) { added = 0; removed = 0; if(backup) { string destDir = Path.GetDirectoryName(destinationFile); string file = Path.GetFileName(destinationFile); File.Copy(destinationFile, destDir + "\\Backup of " + file, true); } string tempFile = Path.GetDirectoryName(destinationFile) + "\\__TempOutput.resx"; // Load files in memory MemoryStream sourceStream = new MemoryStream(), destinationStream = new MemoryStream(); FileStream fs; int read; byte[] buffer = new byte[1024]; fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read); read = 0; do { read = fs.Read(buffer, 0, buffer.Length); sourceStream.Write(buffer, 0, read); } while(read > 0); fs.Close(); fs = new FileStream(destinationFile, FileMode.Open, FileAccess.Read, FileShare.Read); read = 0; do { read = fs.Read(buffer, 0, buffer.Length); destinationStream.Write(buffer, 0, read); } while(read > 0); fs.Close(); sourceStream.Position = 0; destinationStream.Position = 0; // Create resource readers ResXResourceReader source = new ResXResourceReader(sourceStream); ResXResourceReader destination = new ResXResourceReader(destinationStream); // Create resource writer if(File.Exists(tempFile)) File.Delete(tempFile); ResXResourceWriter writer = new ResXResourceWriter(tempFile); // Compare source and destination: // for each key in source, check if it is present in destination // if not, add to the output // for each key in destination, check if it is present in source // if so, add it to the output // Find new keys and add them to the output foreach(DictionaryEntry d in source) { bool found = false; foreach(DictionaryEntry dd in destination) { if(d.Key.ToString().Equals(dd.Key.ToString())) { // Found key found = true; break; } } if(!found) { // Add the key writer.AddResource(d.Key.ToString(), d.Value); added++; if(verbose) { Console.WriteLine("Added new key '" + d.Key.ToString() + "' with value '" + d.Value.ToString() + "'\n"); } } } if(addOnly) { foreach(DictionaryEntry d in destination) { writer.AddResource(d.Key.ToString(), d.Value); } } else { int tot = 0; int rem = 0; // Find un-modified keys and add them to the output foreach(DictionaryEntry d in destination) { bool found = false; tot++; foreach(DictionaryEntry dd in source) { if(d.Key.ToString().Equals(dd.Key.ToString())) { // Found key found = true; } } if(found) { writer.AddResource(d.Key.ToString(), d.Value); rem++; } else if(verbose) { Console.WriteLine("Removed deleted key '" + d.Key.ToString() + "' with value '" + d.Value.ToString() + "'\n"); } } removed = tot - rem; } source.Close(); destination.Close(); writer.Close(); // Copy tempFile into destinationFile File.Copy(tempFile, destinationFile, true); File.Delete(tempFile); }
public static Boolean UpdateResourceFile(String key, String value, String path) { Hashtable resourceEntries = new Hashtable(); //Get existing resources if (File.Exists(path)) { ResXResourceReader reader = new ResXResourceReader(path); if (reader != null) { IDictionaryEnumerator id = reader.GetEnumerator(); foreach (DictionaryEntry d in reader) { if (d.Value == null) resourceEntries.Add(d.Key.ToString(), ""); else resourceEntries.Add(d.Key.ToString(), d.Value.ToString()); } reader.Close(); } } //Modify resources here... var updDone = false; if (resourceEntries.ContainsKey(key)) { if ((string) resourceEntries[key] != value) { resourceEntries[key] = value; updDone = true; } } else { resourceEntries.Add(key,value); updDone = true; } //Write the combined resource file if (updDone) { ResXResourceWriter resourceWriter = new ResXResourceWriter(path); foreach (String key2 in resourceEntries.Keys) { resourceWriter.AddResource(key2, resourceEntries[key2]); } resourceWriter.Generate(); resourceWriter.Close(); } return updDone; }
private void CompileLanguagePack() { try { string locale = this.SelectedLocale; Resources ds = grdResources.DataSource as Resources; DeleteTmpDir(); //create folder structure Hashtable files = new Hashtable(); foreach (Resources.ResourceRow row in ds.Resource.Rows) { if (!files.ContainsKey(row.File)) { files.Add( row.File, Path.Combine(this.TmpDirectory, row.File) ); } } Hashtable folders = new Hashtable(); string fullFolderName; foreach (string file in files.Keys) { fullFolderName = Path.GetDirectoryName((string)files[file]); if (!folders.ContainsKey(fullFolderName)) { folders.Add(fullFolderName, fullFolderName); } } foreach (string folder in folders.Keys) { if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } } //write resources to resx files string fullFileName; ResXResourceWriter writer = null; foreach (string file in files.Keys) { string filter = string.Format("File = '{0}'", file); DataRow[] rows = ds.Resource.Select(filter, "File"); if (rows.Length > 0) { fullFileName = (string)files[file]; fullFileName = string.Format("{0}{1}{2}.{3}{4}", Path.GetDirectoryName(fullFileName), Path.DirectorySeparatorChar, Path.GetFileNameWithoutExtension(fullFileName), locale, Path.GetExtension(fullFileName) ); writer = new ResXResourceWriter(fullFileName); foreach (DataRow row in rows) { if (row["Value"] != DBNull.Value) { writer.AddResource((string)row["Key"], (string)row["Value"]); } } writer.Close(); } } if (!Directory.Exists(LanguagePacksDirectory)) { Directory.CreateDirectory(LanguagePacksDirectory); } //zip lang pack string zipFile = string.Format("WebsitePanel Language Pack {0} {1}.zip", locale, GetApplicationVersion()); ZipUtils.Zip("Tmp", "LanguagePacks\\" + zipFile); DeleteTmpDir(); FinishProgress(); string message = string.Format("{0} language pack compiled successfully to\n\"{1}\"", cbSupportedLocales.Text, zipFile); MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { if (IsThreadAbortException(ex)) return; } }
private static bool OutputAltResx(string file, string locale) { Console.WriteLine("Processing: " + file); ResXResourceReader resxReader = new ResXResourceReader(file); FileInfo currentResxFile = new FileInfo(file); string newResxFileName = String.Format("{0}.{1}{2}", currentResxFile.FullName.Substring(0, currentResxFile.FullName.Length - 5), locale, currentResxFile.Extension); ResXResourceWriter resxWriter = new ResXResourceWriter(newResxFileName); foreach (DictionaryEntry resource in resxReader) { if ("Sidebar.WidthInPixels".Equals(resource.Key)) { resxWriter.AddResource(resource.Key.ToString(), "225"); continue; } if (resource.Value.GetType() == typeof(string)) resxWriter.AddResource(resource.Key.ToString(), MungeResource(resource.Value as string, StaticKeyValue(resource.Key.ToString()))); else resxWriter.AddResource(resource.Key.ToString(), resource.Value); } resxWriter.Generate(); resxWriter.Close(); return true; }
private int WriteResource(IResource resource) { IEmbeddedResource embeddedResource = resource as IEmbeddedResource; if (embeddedResource != null) { try { byte[] buffer = embeddedResource.Value; string fileName = Path.Combine(_outputDirectory, resource.Name); if (resource.Name.EndsWith(".resources")) { fileName = Path.ChangeExtension(fileName, ".resx"); using (MemoryStream ms = new MemoryStream(embeddedResource.Value)) { ResXResourceWriter resxw = new ResXResourceWriter(fileName); IResourceReader reader = new ResourceReader(ms); IDictionaryEnumerator en = reader.GetEnumerator(); while (en.MoveNext()) { resxw.AddResource(en.Key.ToString(), en.Value); } reader.Close(); resxw.Close(); } } else // other embedded resource { if (buffer != null) { using (Stream stream = File.Create(fileName)) { stream.Write(buffer, 0, buffer.Length); } } } AddToProjectFiles(fileName); return 0; } catch (Exception ex) { WriteLine("Error in " + resource.Name + " : " + ex.Message); } } return WriteOtherResource(resource); }
public void AddResource_WithComment () { ResXResourceWriter w = new ResXResourceWriter (fileName); ResXDataNode node = new ResXDataNode ("key", "value"); node.Comment = "comment is preserved"; w.AddResource (node); w.Generate (); w.Close (); ResXResourceReader r = new ResXResourceReader (fileName); ITypeResolutionService typeres = null; r.UseResXDataNodes = true; int count = 0; foreach (DictionaryEntry o in r) { string key = o.Key.ToString(); node = (ResXDataNode)o.Value; string value = node.GetValue (typeres).ToString (); string comment = node.Comment; Assert.AreEqual ("key", key, "key"); Assert.AreEqual ("value", value, "value"); Assert.AreEqual ("comment is preserved", comment, "comment"); Assert.AreEqual (0, count, "too many nodes"); count++; } r.Close (); File.Delete (fileName); }
private static void TranslateSingleFile(string fileName, string fileSaveName, bool includeBlankResources) { // Open the input file. ResXResourceReader reader = new ResXResourceReader(fileName); try { // Get the enumerator. If this throws an ArguementException // it means the file is not a .RESX file. IDictionaryEnumerator enumerator = reader.GetEnumerator(); } catch (ArgumentException ex) { Console.WriteLine("WARNING: could not parse " + fileName); Console.WriteLine(" " + ex.Message); return; } // Allocate the list for this instance. SortedList textResourcesList = new SortedList(); // Run through the file looking for only true text related // properties and only those with values set. foreach (DictionaryEntry dic in reader) { // Only consider this entry if the value is something. if (null != dic.Value) { // Is this a System.String. if ("System.String" == dic.Value.GetType().ToString()) { String KeyString = dic.Key.ToString(); // Make sure the key name does not start with the // "$" or ">>" meta characters and is not an empty // string (or we're explicitly including empty strings). if ((false == KeyString.StartsWith(">>")) && (false == KeyString.StartsWith("$")) && (includeBlankResources || "" != dic.Value.ToString())) { // We've got a winner. textResourcesList.Add(dic.Key, dic.Value); } // Special case the Windows Form "$this.Text" or // I don't get the form titles. if (0 == String.Compare(KeyString, "$this.Text")) { textResourcesList.Add(dic.Key, dic.Value); } } } } // It's entirely possible that there are no text strings in the // .ResX file. if (textResourcesList.Count > 0) { if (null != fileSaveName) { if (File.Exists(fileSaveName)) File.Delete(fileSaveName); // Create the new file. ResXResourceWriter writer = new ResXResourceWriter(fileSaveName); foreach (DictionaryEntry textdic in textResourcesList) { writer.AddResource(textdic.Key.ToString(), Psuedoizer.ConvertToFakeInternationalized(textdic.Value.ToString())); } writer.Generate(); writer.Close(); Console.WriteLine(String.Format("{0}: converted {1} text resource(s).", fileName, textResourcesList.Count)); } } else { Console.WriteLine("WARNING: No text resources found in " + fileName); } }
public void TestWriter () { ResXResourceWriter w = new ResXResourceWriter (fileName); w.AddResource ("String", "hola"); w.AddResource ("String2", (object) "hello"); w.AddResource ("Int", 42); w.AddResource ("Enum", PlatformID.Win32NT); w.AddResource ("Convertible", new Point (43, 45)); w.AddResource ("Serializable", new ArrayList (new byte [] { 1, 2, 3, 4 })); w.AddResource ("ByteArray", new byte [] { 12, 13, 14 }); w.AddResource ("ByteArray2", (object) new byte [] { 15, 16, 17 }); w.AddResource ("IntArray", new int [] { 1012, 1013, 1014 }); w.AddResource ("StringArray", new string [] { "hello", "world" }); w.AddResource ("Image", new Bitmap (1, 1)); w.AddResource ("StrType", new MyStrType ("hello")); w.AddResource ("BinType", new MyBinType ("world")); try { w.AddResource ("NonSerType", new MyNonSerializableType ()); Assert.Fail ("#0"); } catch (InvalidOperationException) { } w.Generate (); w.Close (); ResXResourceReader r = new ResXResourceReader (fileName); Hashtable h = new Hashtable (); foreach (DictionaryEntry e in r) { h.Add (e.Key, e.Value); } r.Close (); Assert.AreEqual ("hola", (string) h ["String"], "#1"); Assert.AreEqual ("hello", (string) h ["String2"], "#2"); Assert.AreEqual (42, (int) h ["Int"], "#3"); Assert.AreEqual (PlatformID.Win32NT, (PlatformID) h ["Enum"], "#4"); Assert.AreEqual (43, ((Point) h ["Convertible"]).X, "#5"); Assert.AreEqual (2, (byte) ((ArrayList) h ["Serializable"]) [1], "#6"); Assert.AreEqual (13, ((byte []) h ["ByteArray"]) [1], "#7"); Assert.AreEqual (16, ((byte []) h ["ByteArray2"]) [1], "#8"); Assert.AreEqual (1013, ((int []) h ["IntArray"]) [1], "#9"); Assert.AreEqual ("world", ((string []) h ["StringArray"]) [1], "#10"); Assert.AreEqual (typeof (Bitmap), h ["Image"].GetType (), "#11"); Assert.AreEqual ("hello", ((MyStrType) h ["StrType"]).Value, "#12"); Assert.AreEqual ("world", ((MyBinType) h ["BinType"]).Value, "#13"); File.Delete (fileName); }
public void SaveFile(string filename, Stream stream) { switch (Path.GetExtension(filename).ToLowerInvariant()) { // write XML resource case ".resx": ResXResourceWriter rxw = new ResXResourceWriter(stream); foreach (KeyValuePair<string, ResourceItem> entry in resources) { if (entry.Value != null) { ResourceItem item = entry.Value; rxw.AddResource(item.Name, item.ResourceValue); } } foreach (KeyValuePair<string, ResourceItem> entry in metadata) { if (entry.Value != null) { ResourceItem item = entry.Value; rxw.AddMetadata(item.Name, item.ResourceValue); } } rxw.Generate(); rxw.Close(); break; // write default resource default: ResourceWriter rw = new ResourceWriter(stream); foreach (KeyValuePair<string, ResourceItem> entry in resources) { ResourceItem item = (ResourceItem)entry.Value; rw.AddResource(item.Name, item.ResourceValue); } rw.Generate(); rw.Close(); break; } }
/// <summary> /// The main entry point for the application. /// </summary> public void Run(string fileName, string fileSaveName) { // Open the input file. ResXResourceReader reader = new ResXResourceReader(fileName); try { // Get the enumerator. If this throws an ArguementException // it means the file is not a .RESX file. IDictionaryEnumerator enumerator = reader.GetEnumerator(); // Allocate the list for this instance. SortedList textResourcesList = new SortedList(); // Run through the file looking for only true text related // properties and only those with values set. foreach (DictionaryEntry dic in reader) { // Only consider this entry if the value is something. if (null != dic.Value) { // Is this a System.String. if ("System.String" == dic.Value.GetType().ToString()) { String KeyString = dic.Key.ToString(); // Make sure the key name does not start with the // "$" or ">>" meta characters and is not an empty // string. if ((false == KeyString.StartsWith(">>")) && (false == KeyString.StartsWith("$")) && ("" != dic.Value.ToString())) { // We've got a winner. textResourcesList.Add(dic.Key, dic.Value); } // Special case the Windows Form "$this.Text" or // I don't get the form titles. if (0 == String.Compare(KeyString, "$this.Text")) { textResourcesList.Add(dic.Key, dic.Value); } } } } // It's entirely possible that there are no text strings in the // .ResX file. if (textResourcesList.Count > 0) { if (null != fileSaveName) { // Create the new file. ResXResourceWriter writer = new ResXResourceWriter(fileSaveName); foreach (DictionaryEntry textdic in textResourcesList) { writer.AddResource(textdic.Key.ToString(), Psuedoizer.ConvertToFakeInternationalized(textdic.Value.ToString())); } writer.Generate(); writer.Close(); Console.WriteLine("Converted " + textResourcesList.Count + " text resource(s)."); } } else { Console.Write("WARNING: No text resources found in " + fileName); System.Environment.Exit(2); } } catch (Exception e) { Console.Write(e.ToString()); System.Environment.Exit(1); } }