ConsoleMirror.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // --------------------------------------------------
  2. // UnityInjector - ConsoleMirror.cs
  3. // Copyright (c) Usagirei 2015 - 2015
  4. // --------------------------------------------------
  5. using System;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Text;
  9. namespace UnityInjector.ConsoleUtil
  10. {
  11. internal class ConsoleMirror : IDisposable
  12. {
  13. private readonly MirrorWriter _tWriter;
  14. public ConsoleMirror(string path)
  15. {
  16. try
  17. {
  18. var fileStream = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read);
  19. var fileWriter = new StreamWriter(fileStream)
  20. {
  21. AutoFlush = true
  22. };
  23. _tWriter = new MirrorWriter(fileWriter, Console.Out);
  24. }
  25. catch (Exception e)
  26. {
  27. SafeConsole.ForegroundColor = ConsoleColor.DarkGray;
  28. Console.WriteLine("Couldn't open file to write: {0}", Path.GetFileName(path));
  29. Console.WriteLine(e.Message);
  30. SafeConsole.ForegroundColor = ConsoleColor.Gray;
  31. return;
  32. }
  33. Console.SetOut(_tWriter);
  34. Console.WriteLine();
  35. var processName = Process.GetCurrentProcess().ProcessName;
  36. var now = DateTime.Now;
  37. Console.WriteLine($" {processName} - {now:dd-MM-yyyy hh:mm:ss} ".PadCenter(79, '='));
  38. Console.WriteLine();
  39. }
  40. public void Dispose()
  41. {
  42. var cOld = _tWriter.Console;
  43. var fOld = _tWriter.File;
  44. Console.SetOut(cOld);
  45. if (fOld == null)
  46. return;
  47. fOld.Flush();
  48. fOld.Close();
  49. }
  50. private class MirrorWriter : TextWriter
  51. {
  52. public TextWriter Console { get; }
  53. public override Encoding Encoding => File.Encoding;
  54. public TextWriter File { get; }
  55. public MirrorWriter(TextWriter file, TextWriter console)
  56. {
  57. File = file;
  58. Console = console;
  59. }
  60. public override void Flush()
  61. {
  62. File.Flush();
  63. Console.Flush();
  64. }
  65. public override void Write(char value)
  66. {
  67. File.Write(value);
  68. Console.Write(value);
  69. }
  70. }
  71. }
  72. }