将值从字典对象写入文本文件,仅写入最后一个键值对

问题描述

我根本不了解C#或任何编程,但是我想学习。我最近几天一直在网上搜索,以整理应该从2个文本文件中读取的内容输出一个文件(格式化为json文件的格式,我将其复制/粘贴到该文件中)。因此,我可以从两个文件中读取,创建字典对象并写入文件,但它仅写入最后一个项目。我相信我会一遍又一遍地覆盖,直到最后一部分。如何附加到文件而不是覆盖?

我的代码

using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WriteLangFile
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string path1 = @"C:\temp\langVars.txt";
                string path2 = @"C:\temp\langValues.txt";

                string[] readVars = File.ReadAllLines(path1);
                string[] readVals = File.ReadAllLines(path2);

                Dictionary<string,string> dictionaryVars = new Dictionary<string,string>();
                for (int i = 0; i < readVars.Length; i++)
                {
                    dictionaryVars.Add(readVars[i],readVals[i]);
                }

                string outputPath = ("C:\\temp\\");
                string outputFileName = ("lang.txt");
                string constant,value;

                foreach (keyvaluePair<string,string> kvp in dictionaryVars)
                {
                    constant = (kvp.Key);
                    value = (kvp.Value);
                    string[] lines = { ("\"LANG_\"" + constant + "\"_LANG \"" + " : { "),("\"translations\" : {"),("\"Lang.asp\" : {"),("\"eng\"" + ": \"" + value + "\""),("}"),("},")
                    };

                    using (StreamWriter outFile = new StreamWriter(Path.Combine(outputPath,outputFileName)))
                    {
                        foreach (var item in lines)
                        {
                            outFile.WriteLine(item.ToString());
                        }

                    }

                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

解决方法

您的问题是,您正在循环中打开/关闭文件,而没有使用constructor of StreamWriter that takes the append option

最好的解决方案可能是将StreamWriter的创建移出循环,以便只打开一次文件:

using (StreamWriter outFile = new StreamWriter(Path.Combine(outputPath,outputFileName)))
{
    foreach (KeyValuePair<string,string> kvp in dictionaryVars)
    {
        constant = (kvp.Key);
        value = (kvp.Value);
        string[] lines = { ("\"LANG_\"" + constant + "\"_LANG \"" + " : { "),("\"translations\" : {"),("\"Lang.asp\" : {"),("\"eng\"" + ": \"" + value + "\""),("}"),("},")
        };

        foreach (var item in lines)
        {
            outFile.WriteLine(item.ToString());
        }
    }
}

为了完整起见,如果要将StreamWriter创建的内容保留在循环中,则可以这样构造它,以便它追加而不是覆盖文件:

using (StreamWriter outFile = new StreamWriter(Path.Combine(outputPath,outputFileName),append: true))

P.S。看来您可能正在尝试生成其中包含JSON的文件。目前,您的代码无法生成有效的JSON。如果要生成JSON,则应使用JSON.NET之类的序列化程序,而不要手动构建JSON(即,以易于出错的方式)。