Search code examples
c#loopsdictionaryappendconsole.writeline

Writing values from dictionary object to text file only writing last key value pair


I don't know C# or any programming that well at all, but I want to learn. I've been searching online last couple days to put together what is supposed to read from 2 text files and output a file (formatted for a json file that I'll just copy/paste into that file). So I can read from two files, create a dictionary object and write to a file but it's only writing the last item. I believe I'm overwriting over and over until the last part. How do I append to the file rather than overwrite?

My code:

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.");
            }
        }
    }
}

Solution

  • Your issue is that you're opening/closing the file within the loop, and you're not using the constructor of StreamWriter that takes the append option.

    The best solution is probably to move StreamWriter creation outside of the loop so that you only open the file once:

    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());
            }
        }
    }
    

    For completeness, if you were to keep the StreamWriter creation within the loop, you could construct it like this so that it appends rather than overwriting the file:

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

    P.S. It looks like you might be trying to generate a file with JSON inside it. At present your code does not generate valid JSON. If you want to generate JSON, you should use a serializer such as JSON.NET rather than building the JSON manually (i.e. in an error-prone way).