读取配置文件并创建日志文件
本文关键字:日志 文件 创建 配置文件 读取 | 更新日期: 2023-09-27 17:58:42
我有一个名为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);
}
}
因此,基本上,您有一个包含要写入的日志文件路径的配置文件;但是你并没有说任何关于日志文件的内容。你只是想知道在哪里创建它,对吗?
类似的东西
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#类,将其序列化为XML文件,然后在启动应用程序时进行反序列化。然后,只要您需要,就可以在类中获得可用的配置。
//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);