Sunday, May 20, 2012

Process

More cool stuff from Chapter 5 of C# 4.0 in a Nutshell: Process! The first test below will open up a file in the Notepad. The second test will reach into a command line shell and then pull out the copy given when one types ipconfig. The book suggests the shell itself will be suppressed with the "UseShellExecute = false" stuff, but on my end I see shell flicker open and then close really quickly. Whatever. Neat stuff. Use Process to reach out to other apps on your PC from C#! Hell yes!

using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Whatever.Tests
{
   [TestClass]
   public class ProcessTests
   {
      [TestMethod]
      public void NotepadTest()
      {
         TextWriter writer = new StreamWriter("C:\\Tom.txt");
         writer.Write("Hello World");
         writer.Close();
         Process.Start("Notepad.exe", "C:\\Tom.txt");
         TextReader reader = new StreamReader("C:\\Tom.txt");
         string whatWasRead = reader.ReadToEnd();
         reader.Close();
         Assert.AreEqual(whatWasRead, "Hello World");
      }
      
      [TestMethod]
      public void CommandLineTest()
      {
         ProcessStartInfo processInfo = new ProcessStartInfo();
         processInfo.FileName = "cmd.exe";
         processInfo.Arguments = "/c ipconfig /all";
         processInfo.RedirectStandardOutput = true;
         processInfo.UseShellExecute = false;
         Process process = Process.Start(processInfo);
         string ipInfo = process.StandardOutput.ReadToEnd();
         Assert.IsTrue(ipInfo.Contains("192.168.1.65"));
      }
   }
}

No comments:

Post a Comment