1+ using System . Diagnostics ;
2+ using System . IO ;
3+
4+ namespace RevitDevTool . Models ;
5+
6+ /// <summary>
7+ /// Redirects Console.WriteLine output to the Trace system
8+ /// </summary>
9+ public class ConsoleRedirector : IDisposable
10+ {
11+ private readonly TextWriter _originalOut ;
12+ private readonly TextWriter _originalError ;
13+ private readonly ConsoleTextWriter _consoleOutWriter ;
14+ private readonly ConsoleTextWriter _consoleErrorWriter ;
15+ private bool _disposed ;
16+
17+ public ConsoleRedirector ( )
18+ {
19+ _originalOut = Console . Out ;
20+ _originalError = Console . Error ;
21+
22+ _consoleOutWriter = new ConsoleTextWriter ( TraceEventType . Verbose ) ;
23+ _consoleErrorWriter = new ConsoleTextWriter ( TraceEventType . Error ) ;
24+
25+ Console . SetOut ( _consoleOutWriter ) ;
26+ Console . SetError ( _consoleErrorWriter ) ;
27+ }
28+
29+ public void Dispose ( )
30+ {
31+ if ( ! _disposed )
32+ {
33+ Console . SetOut ( _originalOut ) ;
34+ Console . SetError ( _originalError ) ;
35+ _consoleOutWriter . Dispose ( ) ;
36+ _consoleErrorWriter . Dispose ( ) ;
37+ _disposed = true ;
38+ }
39+ GC . SuppressFinalize ( this ) ;
40+ }
41+
42+ private class ConsoleTextWriter : TextWriter
43+ {
44+ private readonly TraceEventType _eventType ;
45+
46+ public ConsoleTextWriter ( TraceEventType eventType )
47+ {
48+ _eventType = eventType ;
49+ }
50+
51+ public override void Write ( string ? value )
52+ {
53+ if ( string . IsNullOrEmpty ( value ) )
54+ return ;
55+
56+ switch ( _eventType )
57+ {
58+ case TraceEventType . Error :
59+ case TraceEventType . Critical :
60+ Trace . TraceError ( value ) ;
61+ break ;
62+ case TraceEventType . Warning :
63+ Trace . TraceWarning ( value ) ;
64+ break ;
65+ case TraceEventType . Information :
66+ Trace . TraceInformation ( value ) ;
67+ break ;
68+ case TraceEventType . Verbose :
69+ case TraceEventType . Start :
70+ case TraceEventType . Stop :
71+ case TraceEventType . Suspend :
72+ case TraceEventType . Resume :
73+ case TraceEventType . Transfer :
74+ default :
75+ Trace . WriteLine ( value ) ;
76+ break ;
77+ }
78+ }
79+
80+ public override void WriteLine ( string ? value )
81+ {
82+ if ( value != null ) Write ( value ) ;
83+ }
84+
85+ public override System . Text . Encoding Encoding => System . Text . Encoding . UTF8 ;
86+ }
87+ }
0 commit comments