High-Performance Development - C#, VB, SQL, ASP.NET

Slogan Text

This article describes how to execute an external program in ASP.NET.

Problem: We need to decompress hundreds of compressed data files.

Solution: Write a C# class to decompress a single compressed file using the System.Diagnostics.Process.Start method.

We have an external program called, decompress.exe, which accepts two command line parameters:

Input File: Compressed File Path
Output File: Decomprssed File Path

Here are the steps to decompress the file and read the plaintext data into our program:

  1. The caller passes the physical application file path and file name of the compressed file as the parameter to the Process method.
  2. Create the output decompressed file name by changing the file extension using Path.ChangeExtension.
  3. Format the full command line with the two file paths.
  4. Call System.Diagnostics.Process.Start
  5. Pass the file path and external application name as parameter #1.
  6. Pass the command line arguments as parameter #2.
  7. Wait for the external program to complete by calling WaitForExit() method.
  8. Read external program output using a StreamReader.
using System.Diagnostics;
using System.IO;

    public class Decompress
    {
        private string m_CommandLine = "{0} {1}";
        private string m_DecompressAppFilePath = "{0}decompress.exe";
        private StringBuilder m_ReportObj = null;
    
        public Decompress(string FilePath)
        {
            // Caller passes in Physical Application Path to executable.
            m_DecompressAppFilePath = String.Format(m_DecompressAppFilePath, FilePath);
        }
        
        public bool Process(string FilePath)
        {
            string CommandLine = "";
            string OutputFilePath = "";
            System.Diagnostics.Process ProcessObj;
            StreamReader ReaderObj;

            OutputFilePath = Path.ChangeExtension(".compressed", ".decompressed");

            CommandLine = String.Format(m_CommandLine, FilePath, OutputFilePath);

            try
            {
                ProcessObj = System.Diagnostics.Process.Start(m_DecompressAppFilePath, CommandLine);
            }
            catch
            {
                return false;
            }

            ProcessObj.WaitForExit();

            ReaderObj = new StreamReader(OutputFilePath);

            m_ReportObj = new StringBuilder();

            m_ReportObj.Append(ReaderObj.ReadToEnd());        

            return true;
        }
    }