Console Input Output Redirect

Do not ask me why, but I have created a little console project a main aim of which was to redirect input and output streams to files. Because I do not know yet how to insert zip file here (I would like to share a VS2010 project source code) I will just copy-paste the main file. Fortunately the project consists of two “custom” cs files – the first (mentioned as “main”) one where the logic resides, the second one was got from CodeProject (its class parses a command line input). The Code Project code is shared with MIT license so no illegal and stolen content 🙂

namespace Console
{
    class Program
    {
        ///
 /// /// 

        ///args">Example: Console -FileName cmd -InputPath "C:\temp\input.txt" -OutputPath "C:\temp\output.txt"
        static void Main(string[] args)
        {
            LocalWriteLine("Starting...");

            var arguments = new Arguments(args);

            _fileName = arguments["FileName"] ?? DefaultFileName;
            _outputPath = arguments["OutputPath"] ?? DefaultOutputPath;
            _inputPath = arguments["InputPath"] ?? DefaultInputPath;
            _inputFullPath = Path.GetFullPath(_inputPath);

            _writer = !File.Exists(_outputPath) ?
                        File.CreateText(_outputPath)
                        : File.AppendText(_outputPath);

            if (!File.Exists(_inputPath)) File.Create(_inputPath).Close();

            _process = new Process
                              {
                                  StartInfo =
                                      {
                                          UseShellExecute = false,
                                          RedirectStandardInput = true,
                                          RedirectStandardOutput = true,
                                          RedirectStandardError = true,
                                          FileName = _fileName
                                      }
                              };

            _process.OutputDataReceived += ProcessOutputDataReceived;
            _process.ErrorDataReceived += ProcessOutputDataReceived;

            var fsw = new FileSystemWatcher(Path.GetDirectoryName(_inputFullPath))
                          {
                              Filter = Path.GetFileName(_inputPath)
                          };

            fsw.Changed += FswChanged;

            _process.Start();

            _process.BeginErrorReadLine();
            _process.BeginOutputReadLine();
            fsw.EnableRaisingEvents = true;

            _process.WaitForExit();

            LocalWriteLine("Stopping...");

            _writer.Close();
            _process.Close();
            fsw.Dispose();
        }

        static void FswChanged(object sender, FileSystemEventArgs e)
        {
            if (!e.FullPath.Equals(_inputFullPath) || e.ChangeType != WatcherChangeTypes.Changed) return;

            var data = File.ReadAllText(_inputPath);

            if (string.IsNullOrEmpty(data)) return;

            File.WriteAllText(_inputPath, string.Empty);

            LocalWrite(data);

            _process.StandardInput.Write(data);

        }

        static void ProcessOutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            LocalWriteLine(e.Data);
            _writer.WriteLine(e.Data);
            _writer.Flush();
        }

        [Conditional("DEBUG")]
        private static void LocalWriteLine(string data)
        {
            System.Console.WriteLine(data);
        }

        [Conditional("DEBUG")]
        private static void LocalWrite(string data)
        {
            System.Console.Write(data);
        }

        private const string DefaultInputPath = @"input.txt";
        private const string DefaultOutputPath = @"output.txt";
        private const string DefaultFileName = @"cmd";

        private static string _inputPath;
        private static string _inputFullPath;
        private static string _outputPath;
        private static string _fileName;

        private static StreamWriter _writer;
        private static Process _process;
     }
Advertisements
This entry was posted in .NET, C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s