简体   繁体   中英

Output/Log Console.Read & Console.Write from a Console application to a TXT/XML File C#

I have a Console application (C#) that interacts with the User, and every step is shown via Console.Writeline.

Now I wanted to write these events to XML or TXT, and my only guess was to create a List and add all the Console.Writelines to it, but then I noticed that logging the Console.Readline is mandatory, and that's the reason I'm asking this question.

How do I log Console.Reads/Console.Writes to a TXT/XML?

Thank you.

The simplest way to accomplish this is to use File.AppendAllText

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.

Something like this

string line = Console.ReadLine();
Console.WriteLine(line); // I gather you want to write it out again?
File.AppendAllText(@"C:\SomePath\MyFile.txt", line);

If you would prefer to gather all of the text first and then write it all out when your program exits, you could do something like this:

List<string> inputLines = new List<string>();

// Loop here getting lines
string line = Console.ReadLine();
inputLines.Add(line);

// When done:
File.WriteAllLines(@"C:\SomePath\MyFile.txt", inputLines.ToArray());

See

http://msdn.microsoft.com/en-us/library/92e05ft3

我建议您使用log4net ,它是.net的免费日志记录工具

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM