Introduction
I will try to explain
how any .NET executable file can be run inside the ASP.NET environment and exceptions from
the executable file caught as well.
Background
If you search on
line with title like "Execute any executable from asp.net" you can
find various solution with code example. But when you want to handle any
exception thrown from the executable file, you cannot catch that exception.
Common Solution may found
You can find many code example. one code
example like as follows:
try
{
System.Diagnostics.Process process1 = new System.Diagnostics.Process();
process1.StartInfo.FileName = @"c:\temp\File1.exe";
process1.StartInfo.Arguments = "args";
process1.Start();
process1.WaitForExit();
Thread.Sleep(20000); process1.Close();
}
catch (Exception ex)
{
Logger.log(ex.Message);
}
Issue with above code
Code is working
fine. Where the issue is? Well, you can change you .exe file code and throw
exception from that executable. Then you see that you cannot catch that
exception from current solution.
Why not catch exception?
When you run any
.exe file with the Process object it then create a new independent process and
run .exe under that process. For that reason you cannot catch exception. Then what will be
solution?
What will be the solution?
.NET AppDomain
comes with a solution. First you need to create a AppDomain, then .exe file
should run inside that AppDomain. AppDomain will not create any independent
process, instead it create a isolated environment, this environment will create
under current assembly process and any time you can destroy it without any
problem.
Is it possible to provide example with code?
The solution code
are as follows
try
{
AppDomain sandBox = AppDomain.CreateDomain("sandBox");
try
{
sandBox.ExecuteAssembly(".exe file name with path");
}
finally
{
AppDomain.Unload(sandBox); }
}
catch (Exception ex){
}
Points of Interest
I found a
limitation on that solution. The limitation is Executable (.exe) must be .NET
assembly. No native .exe will work there.