[英]c# how to save dictionary to a text file
我正在嘗試將字典保存在 txt 文件中,我正在尋找簡單的示例。你能幫我嗎? 我正在嘗試這個,但它對我不起作用。謝謝。
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))
你可以用File.WriteAllLines
和一些 Linq 來做到這一點
File.WriteAllLines(
path,
dictionary.Select(kvp => string.Format("{0};{1}", kvp.Key, kvp.Value));
請注意,這將在遍歷字典時寫入文件,因此不會使用任何額外的內存。
您正在將字典的內容寫入sb
但從未使用過。 無需先創建字典的內存副本(StringBuilder)。 相反,只需在枚舉字典時將其寫出來。
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));
}
}
用:
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();
}
這段代碼創建了一個指向您正在寫入的文件的流,循環遍歷鍵值對並將它們一一寫入文件。 如果成功完成或捕獲到 IO 異常,則應關閉流,否則該文件可能仍被進程打開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.