Search code examples
c#streamreader

Read config file and create a log file


I have a config file called one_two.config.txt containing the path of a log file to be written.

I want to read this line ( 'comdir=C:\Users\One\Desktop' ) and then create a new log file in a given directory. The log file is going to have some data ( Time / Date / ID etc. )

Here is what i have right now :

                   string VarSomeData = ""; // Contains Data that should be written in log.txt

                    for (Int32 i = 0; i < VarDataCount; i++)
                    {                            

                        csp2.DataPacket aPacket;


                        VarData = csp2.GetPacket(out aPacket, i, nComPort);


                        VarSomeData = String.Format("\"{0:ddMMyyyy}\",\"{0:HHmmss}\",\"{1}\",\"{2}\",\"{3}\" \r\n", aPacket.dtTimestamp, VarPersNr, aPacket.strBarData, VarId.TrimStart('0'));


                        string line = "";
                        using (StreamReader sr = new StreamReader("one_two.config.txt"))
                        using (StreamWriter sw = new StreamWriter("log.txt"))
                        {
                            while ((line = sr.ReadLine()) != null)
                            {
                               if((line.StartsWith("comdir="))
                               {
                                 // This is wrong , how should i write it ?
                                 sw.WriteLine(VarSomeData); 
                               }
                            }
                        }
                    }

Right now the log file is being created in same directory as the config file.


Solution

  • This should get you started:

    string line;
    using (StreamReader file = new StreamReader("one_two.config.txt"))
    using (StreamWriter newfile = new StreamWriter("log.txt"))
    {
        while ((line = file.ReadLine()) != null)
        {
            newfile.WriteLine(line);
        }
    }