public static string WriteDictionaryToXml(Dictionary <string, object> dictToWrite, string filename, bool append = false, bool savePreviousFileVersion = false) { FileInfo finfo = new FileInfo(filename); if (!Directory.Exists(finfo.DirectoryName)) { Directory.CreateDirectory(finfo.DirectoryName); } if (File.Exists(filename) && !append && savePreviousFileVersion) { string filename_cp = ServiceTools.NewNumberedFilenameThatDoesntExist(filename); bool success = false; int counter = 0; while ((!success) && (counter <= 10)) { try { File.Move(filename, filename_cp); success = true; } catch (Exception ex) { success = false; counter++; Thread.Sleep(20); } } if (!success) { filename = filename_cp; } } DataSet dsToWrite = new DataSet("DataSet"); dsToWrite.Namespace = "NetFrameWork"; DataTable table = new DataTable("table"); DataColumn keyColumn = new DataColumn("key", Type.GetType("System.String")); DataColumn valueColumn = new DataColumn("value"); table.Columns.Add(keyColumn); table.Columns.Add(valueColumn); dsToWrite.Tables.Add(table); DataRow newRow; if (append && File.Exists(filename)) { Dictionary <string, object> tmpDict = new Dictionary <string, object>(); DataSet readingDataSet = new DataSet("DataSet"); readingDataSet.ReadXml(filename); foreach (DataTable tmpTable in readingDataSet.Tables) { foreach (DataRow row in tmpTable.Rows) { tmpDict.Add(row[0] as string, row[1]); } } readingDataSet.Dispose(); foreach (KeyValuePair <string, object> pair in tmpDict) { newRow = table.NewRow(); newRow["key"] = pair.Key; newRow["value"] = pair.Value; table.Rows.Add(newRow); } File.Delete(filename); } foreach (KeyValuePair <string, object> pair in dictToWrite) { newRow = table.NewRow(); newRow["key"] = pair.Key; newRow["value"] = pair.Value; table.Rows.Add(newRow); } dsToWrite.AcceptChanges(); bool sucess = false; int tries = 0; while ((!sucess) && (tries <= 10)) { try { dsToWrite.WriteXml(filename); sucess = true; } catch (Exception ex) { Thread.Sleep(20); sucess = false; tries++; } } dsToWrite.Dispose(); return(filename); }