读取配置文件并创建日志文件

Read config file and create a log file

我有一个名为 one_two.config.txt 的配置文件,其中包含要写入的日志文件的路径。

我想阅读这一行 ('comdir=C:\Users\One\Desktop'),然后在给定目录中创建一个新的日志文件。 日志文件将包含一些数据(时间/日期/ID 等)

这是我现在拥有的:

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

现在正在与配置文件相同的目录中创建日志文件。

这应该让你开始:

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);
    }
}
//Input file path
string inPath = "C:\Users\muthuraman\Desktop\one_two.config.txt";
//Output File path
string outPath = "C:\Users\muthuraman\Desktop\log.txt";
// Below code reads all the lines in the text file and Store the text as array of strings
string[]  input=System.IO.File.ReadAllLines(inPath);
//Below code write all the text in string array to the specified output file
System.IO.File.WriteAllLines(outPath, input);

基本上,您有一个配置文件,其中包含要写入的日志文件的路径;但您并没有说明该日志文件的内容。您只想知道在哪里创建它,对吗?

类似

string ConfigPath = "one_two.config.txt";
string LogPath = File.ReadAllLines(ConfigPath).Where(l => l.StartsWith("comdir=")).FirstOrDefault()
if (!String.IsNullOrEmpty(LogPath)) {
  using (TextWriter writer = File.CreateText(LogPath.SubString(7))) {
    writer.WriteLine("Log file created.");
  }
}

您也可以用这种方式阅读配置行,但代码会多一点,但您会获得更好的性能

string LogPath = null;
using (StreamReader file = new System.IO.StreamReader(ConfigPath)) {
  while((line = file.ReadLine()) != null) {
    if (line.StartsWith("comdir="))
      LogPath = line.Substring(7);
  }
}

对于配置文件,您可能需要考虑使用 C# class,将其序列化为 XML 文件,然后在启动应用程序时反序列化。然后,只要您需要,您就可以在 class 中获得配置。