问题
Possible Duplicate:
Mirroring console output to a file
I've a console application in C# and I want to Log into a text file every text appears on the screen. How to do that ?
Unfortunately this thread is closed despite of my comment about the Mirroring console output to a file. The accepted post as answer by that thread IS NOT CORRECT. So why cannot ask the question again? I'm using console interactively and want a copy of all the text on console in a text file. SOS
回答1:
C:\>yourconsoleapp.exe > yourtextfile.txt
edit: This assumes your console app requires no user input.
回答2:
Replace all references to the Console class with the System.Diagnostics.Trace class. You can add a ConsoleTraceListener and a TextWriterTraceListener, and then everything you output to the console will end up in both places.
回答3:
You could use Console.SetOut to redirect the output to a file, but then you wouldn't get output to the console as well unless you used a TextWriter that streamed to both.
You could try using System.Diagnostics.Trace and then adding listeners to both the console and a file.
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="configConsoleListener"
type="System.Diagnostics.ConsoleTraceListener" />
<add name="fileLogger"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="LogFile.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
回答4:
This may be overly simplistic, but at a command prompt, if you do:
C:\>MyApplication >> output.txt
That will write all output from that given app to output.txt
If you don't actually need a programmatic solution, this might do the trick.
回答5:
A simple Google search result : here
Sorry I am no longer programming with C# but I checked to code and it does make sense in this approach :)
回答6:
Use log4j.
- Go to log4j website and download dll.
- Reference dll in your project.
- Add this to top of your app.config
<appender name="FileAppender" type="log4net.Appender.FileAppender"> <file value="log-file.txt" /> <appendToFile value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] -%message%newline" /> </layout> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] -%message%newline" /> </layout> </appender>
Put this as a member of any class you want to log to:
private static readonly ILog log = LogManager.GetLogger(typeof(Foo));
Put in a line like this to log:
log.Debug("Hello world!");
来源:https://stackoverflow.com/questions/3886895/how-to-log-console-screen-into-a-text-file