001 // Define the namespaces used by this sample.
002 using System;
003 using System.Text;
004 using System.Globalization;
005 using System.IO;
006 using System.Diagnostics;
007 using System.Threading;
008 using System.ComponentModel;
009   
010   
011 namespace ProcessAsyncStreamSamples
012 {
013   
014     class ProcessNetStreamRedirection
015     {
016         // Define static variables shared by class methods.
017         private static StreamWriter streamError =null;
018         private static String netErrorFile = "";
019         private static StringBuilder netOutput = null;
020         private static bool errorRedirect = false;
021         private static bool errorsWritten = false;
022   
023         public static void RedirectNetCommandStreams()
024         {
025             String netArguments;
026             Process netProcess;
027   
028             // Get the input computer name.
029             Console.WriteLine("Enter the computer name for the net view command:");
030             netArguments = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture);
031             if (String.IsNullOrEmpty(netArguments))
032             {
033                 // Default to the help command if there is not an input argument.
034                 netArguments = "/?";
035             }
036   
037             // Check if errors should be redirected to a file.
038             errorsWritten = false;
039             Console.WriteLine("Enter a fully qualified path to an error log file");
040             Console.WriteLine("  or just press Enter to write errors to console:");
041             netErrorFile = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture);
042             if (!String.IsNullOrEmpty(netErrorFile))
043             {
044                 errorRedirect = true;
045             }
046   
047             // Note that at this point, netArguments and netErrorFile
048             // are set with user input.  If the user did not specify
049             // an error file, then errorRedirect is set to false.
050   
051             // Initialize the process and its StartInfo properties.
052             netProcess = new Process();
053             netProcess.StartInfo.FileName = "Net.exe";
054   
055             // Build the net command argument list.
056             netProcess.StartInfo.Arguments = String.Format("view {0}"
057                 netArguments);
058   
059             // Set UseShellExecute to false for redirection.
060             netProcess.StartInfo.UseShellExecute = false;
061   
062             // Redirect the standard output of the net command.  
063             // This stream is read asynchronously using an event handler.
064             netProcess.StartInfo.RedirectStandardOutput = true;
065             netProcess.OutputDataReceived += new DataReceivedEventHandler(NetOutputDataHandler);
066             netOutput = new StringBuilder();
067   
068             if (errorRedirect)
069             {
070                 // Redirect the error output of the net command. 
071                 netProcess.StartInfo.RedirectStandardError = true;
072                 netProcess.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);
073             }
074             else 
075             {
076                 // Do not redirect the error output.
077                 netProcess.StartInfo.RedirectStandardError = false;
078             }
079   
080             Console.WriteLine("/nStarting process: net {0}"
081                 netProcess.StartInfo.Arguments);
082             if (errorRedirect)
083             {
084                 Console.WriteLine("Errors will be written to the file {0}"
085                     netErrorFile);
086             }
087   
088             // Start the process.
089             netProcess.Start();
090   
091             // Start the asynchronous read of the standard output stream.
092             netProcess.BeginOutputReadLine();
093   
094             if (errorRedirect)
095             {
096                 // Start the asynchronous read of the standard
097                 // error stream.
098                 netProcess.BeginErrorReadLine();
099             }
100   
101             // Let the net command run, collecting the output.
102             netProcess.WaitForExit();
103   
104             if (streamError != null)
105             {
106                 // Close the error file.
107                 streamError.Close();
108             }
109             else 
110             {
111                 // Set errorsWritten to false if the stream is not
112                 // open.   Either there are no errors, or the error
113                 // file could not be opened.
114                 errorsWritten = false;
115             }
116   
117             if (netOutput.Length > 0)
118             {
119                 // If the process wrote more than just
120                 // white space, write the output to the console.
121                 Console.WriteLine("/nPublic network shares from net view:/n{0}/n"
122                     netOutput);
123             }
124   
125             if (errorsWritten)
126             {
127                 // Signal that the error file had something 
128                 // written to it.
129                 String [] errorOutput = File.ReadAllLines(netErrorFile);
130                 if (errorOutput.Length > 0)
131                 {
132                     Console.WriteLine("/nThe following error output was appended to {0}.",
133                         netErrorFile);
134                     foreach (String errLine in errorOutput)
135                     {
136                         Console.WriteLine("  {0}", errLine);
137                     }
138                 }
139                 Console.WriteLine();
140             }
141   
142             netProcess.Close();
143   
144         }
145   
146         private static void NetOutputDataHandler(object sendingProcess, 
147             DataReceivedEventArgs outLine)
148         {
149             // Collect the net view command output.
150             if (!String.IsNullOrEmpty(outLine.Data))
151             {
152                 // Add the text to the collected output.
153                 netOutput.Append(Environment.NewLine + "  " + outLine.Data);
154             }
155         }
156   
157         private static void NetErrorDataHandler(object sendingProcess, 
158             DataReceivedEventArgs errLine)
159         {
160             // Write the error text to the file if there is something
161             // to write and an error file has been specified.
162   
163             if (!String.IsNullOrEmpty(errLine.Data))
164             {
165                 if (!errorsWritten)
166                 {
167                     if (streamError == null)
168                     {
169                         // Open the file.
170                         try 
171                         {
172                             streamError = new StreamWriter(netErrorFile, true);
173                         }
174                         catch (Exception e)
175                         {
176                             Console.WriteLine("Could not open error file!");
177                             Console.WriteLine(e.Message.ToString());
178                         }
179                     }
180   
181                     if (streamError != null)
182                     {
183                         // Write a header to the file if this is the first
184                         // call to the error output handler.
185                         streamError.WriteLine();
186                         streamError.WriteLine(DateTime.Now.ToString());
187                         streamError.WriteLine("Net View error output:");
188                     }
189                     errorsWritten = true;
190                 }
191   
192                 if (streamError != null)
193                 {
194                     // Write redirected errors to the file.
195                     streamError.WriteLine(errLine.Data);
196                     streamError.Flush();
197                 }
198             }
199         }
200     }
201 }