【问题标题】:Writing values from dictionary object to text file only writing last key value pair将值从字典对象写入文本文件仅写入最后一个键值对
【发布时间】:2021-01-19 21:37:06
【问题描述】:

我完全不了解 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.");
            }
        }
    }
}

【问题讨论】:

    标签: c# loops dictionary append console.writeline


    【解决方案1】:

    您的问题是您在循环中打开/关闭文件,而您没有使用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))
    

    附:看起来您可能正在尝试生成其中包含 JSON 的文件。目前您的代码不会生成有效的 JSON。如果要生成 JSON,则应使用 JSON.NET 等序列化程序,而不是手动构建 JSON(即以容易出错的方式)。

    【讨论】:

    • 谢谢,append 成功了。当我尝试将它从循环中取出时,foreach 不知道行数组是什么,可以这么说。我不知道 C#,我创建了一个构建 json 的 vbscript 脚本,但只是想在 c# 中尝试一下。我被赋予了一项艰巨的任务,即从包含 1200 多个要添加的项目的电子表格中手动更新 json 文件,因此我在 c# 中尝试了它,用完了时间并用旧的 vbscript 制作了一些东西,但又回到了 c# 中,因为我不能不要尝试完成!是的,我阅读了有关序列化程序的信息,但也没有时间自学。
    • 快速提问,我正在尝试通过在左侧填充它们来格式化数组中的字符串,你知道为什么这不起作用吗? string[] lines = { ("\"LANG_" + 常量 + "_LANG \"" + " : { ").PadLeft(4), ("\"translations\" : {").PadLeft(6, ' ' ), ("\"attLang.asp\" : {").PadLeft(8, ' '), ("\"eng\"" + ":\"" + value + "\"").PadLeft(10 , ' '), ("}").PadLeft(8, ' '), ("}").PadLeft(6, ' '), ("},").PadLeft(4, ' ')
    猜你喜欢
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    相关资源
    最近更新 更多