HomeSearch

C# Convert Dictionary to String (Write to File)

Transform a Dictionary into a string with StringBuilder, and get a Dictionary from a string again.
Convert Dictionary, string. A Dictionary can be converted to string format. This string can then be persisted in a text file and read back into memory.DictionaryStrings
Notes, round trip. With 2 methods, we can round-trip the Dictionary and string. A method like GetDict() can be used in many places in a program.
An example. We write the values of Dictionary types to the disk and then parse them. I had to store a Dictionary of string keys and int values. This is also called serialization.

GetLine: The GetLine method receives a Dictionary that was declared at class-level. It uses a StringBuilder.

StringBuilder

Next: GetLine() iterates through the Dictionary's KeyValuePair collection. It appends the data to a StringBuilder.

ForeachKeyValuePair

GetDict: Next, we must get a new Dictionary<string, int> from the file we saved it to. GetDict here does that for us.

Split: The string has commas and semicolons as separators. We split on these and consume 2 results in each loop iteration.

Split
C# program that persists Dictionary to file using System; using System.Collections.Generic; using System.IO; using System.Text; class Program { static void Main() { var data = new Dictionary<string, int>() { {"salmon", 5}, {"tuna", 6}, {"clam", 2}, {"asparagus", 3} }; // Get string from Dictionary. string value = GetLine(data); // Save to disk. File.WriteAllText("C:\\programs\\dict.txt", value); // Get dictionary again. var result = GetDict("C:\\programs\\dict.txt"); foreach (var pair in result) { Console.WriteLine("PAIR: " + pair); } } static string GetLine(Dictionary<string, int> data) { // Build up the string data. StringBuilder builder = new StringBuilder(); foreach (var pair in data) { builder.Append(pair.Key).Append( ":").Append(pair.Value).Append(','); } string result = builder.ToString(); // Remove the end comma. result = result.TrimEnd(','); return result; } static Dictionary<string, int> GetDict(string file) { var result = new Dictionary<string, int>(); string value = File.ReadAllText(file); // Split the string. string[] tokens = value.Split(new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries); // Build up our dictionary from the string. for (int i = 0; i < tokens.Length; i += 2) { string name = tokens[i]; string freq = tokens[i + 1]; // Parse the int. int count = int.Parse(freq); // Add the value to our dictionary. if (result.ContainsKey(name)) { result[name] += count; } else { result.Add(name, count); } } return result; } }
Exceptions. Whenever you deal with the file system, your input may become corrupted. So deal with as best you can with exceptions. The two calls above should be wrapped in exceptions.

Recover: Whenever you deal with the file system and your code is not critical, try to recover from any errors.

Tip: Recover by returning an error string, blank string, or just doing nothing.

Exception
A summary. We persisted the Dictionary to the disk and read it back in from the file. You can sometimes develop custom methods to do this with the best performance.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls