How to Execute an External Program
This article describes how to execute an external program in ASP.NET.
The Code
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:
- The caller passes the physical application file path and file name of the compressed file
as the parameter to the Process method.
- Create the output decompressed file name by changing the file
extension using Path.ChangeExtension.
- Format the full command line with the two file paths.
- Call System.Diagnostics.Process.Start
Pass the file path and external application name as parameter #1.
Pass the command line arguments as parameter #2.
- Wait for the external program to complete by calling WaitForExit() method.
- 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;
}
}
|