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

时间:2016-07-27 06:22:21

标签: c# streamreader

我有一个名为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); 
                               }
                            }
                        }
                    }

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

3 个答案:

答案 0 :(得分:3)

这应该让你开始:

{{1}}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

这样的东西
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);
  }
}

对于配置文件,您可能需要考虑使用序列化为XML文件的C#类,然后在启动应用程序时反序列化。然后,您可以在需要时在类中使用配置。