c# - Read a file line by line and write it transformed line by line into another file -
i have read content of existing file "operativedata.txt" line line , write data excelsheet "datawarehouse.csv" line line. content of file "operativedata.txt" looks following in picture (operativedata.txt)):
the data in operativedata.txt have written transformed in different way datawarehouse.csv. have in csv file:
"date;time;randomvalue\n" \n means after these 3 lines return
this type of format have written (all 10 seconds) in datawarehouse.csv file. should @ end: datawarehouse.csv
code generating datawarehouse.csv:
using system; using system.io; using system.threading; namespace etltxt2csv { class program { string[]content;//array reading each line of file operativedata.txt public void loop() { content = file.readalllines(@"c:\etl-process\operativedata.txt");//file read while (true) { (int = 0; < content.length; i++) { thread.sleep(10000); file.appendalltext(@"c:\etl-process\datawarehouse.csv", content[i] + ";" + "\n"); console.writeline(content[i]); } } } static void main(string[] args) { program a= new program(); a.loop(); } } }
operativedata.txt created following code:
using system; using system.threading; using system.io; namespace createdata { class program { string file, date, time; int randomvalue; public void createfile() { file = @"c:\etl-process\operativedata.txt"; date = datetime.now.tostring("yymmdd"); time = datetime.now.tostring("hhmmss"); random random = new random(); while (true) { randomvalue = random.next(200); thread.sleep(10000); file.appendalltext(file, "\r\n" +date + "\r\n" + time + "\r\n" + randomvalue); } } static void main(string[] args) { program = new program(); a.createfile(); } } }
what have change in code of etltxt2csv data can written transformed in way:
"date;time;randomvalue\n" (always first 3 lines in next 3 lines return \n)
into file datawarehouse.csv ?
when i'm executing code of etltxt2 listed here, output of excel file not transformed above in picture (datawarehouse.csv)
agreed jim mischel, 3 lines need read per line in output file.
here's loop if you're keeping same api calls:
(note: it's better memory use , performance use jim mischel's api calls though...)
for (int = 0; + 2 < content.length; += 3) { // console.writeline(content[i] + ";" + content[i+1] + ";" + content[i+2]); file.appendalltext( @"c:\etl-process\datawarehouse.csv", content[i + 0] + ";" + content[i + 1] + ";" + content[i + 2] + "\n" ); }