简体   繁体   中英

c# how to save dictionary to a text file

I am trying to save dictionary in txt file and I am looking for simple examples.Can you help me,please? I am trying this but it does not work for me.Thanks.

Dictionary<string, int> set_names = new Dictionary<string, int>();
        //fill dictionary 
        //then do:
        StringBuilder sb =new StringBuilder();
        foreach (KeyValuePair<string, int> kvp in set_names)
        {
            sb.AppendLine(string.Format("{0};{1}", kvp.Key, kvp.Value));
        }

        string filePath = @"C:\myfile.txt";
        using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
        {
            using (TextWriter tw = new StreamWriter(fs))

You can do this with File.WriteAllLines and some Linq

File.WriteAllLines(
    path, 
    dictionary.Select(kvp => string.Format("{0};{1}", kvp.Key, kvp.Value));

Note that this will write to the file as it loops through the dictionary thus not using any additional memory.

You are writing the contents of your dictionary into sb but never using it. There is no need to first create an in-memory copy of your dictionary (the StringBuilder). Instead, just write it out as you enumerate the dictionary.

string filePath = @"C:\myfile.txt";
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
    using (TextWriter tw = new StreamWriter(fs))

    foreach (KeyValuePair<string, int> kvp in set_names)
    {
        tw.WriteLine(string.Format("{0};{1}", kvp.Key, kvp.Value));
    }
}

Use:

StreamWriter sw = new StreamWriter(YOUFILEPATHSTRING);
try
{
 foreach(KeyValuePair kvp in set_names)
 {
   sw.WriteLine(kvp.Key +";"+kvp.Value;
 }

 sw.Close();
}

catch (IOException ex)
{
 sw.Close();
}

This code create a stream pointed to the file you are writing to, loops over the Key value pairs and write them one by one to the file. The stream should be closed in the event of successful completion or if an IO exception is caught, otherwise the file may still opened by the process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM