views:

264

answers:

5

Can we check if a running application or a program uses .Net framework to execute itself?

A: 

Use System.Reflection.Assembly.LoadFrom function to load the .exe file. This function will throw exception if you try to load binary file that is not .NET assembly.

lubos hasko
-1: He asked about a running application
John Saunders
what difference does it make? running application doesn't have .exe file?
lubos hasko
In that case, please show him how to find the EXE file corresponding to the running program; and show him how to deal with the possibility his process can't get read access to the .EXE file.
John Saunders
Yes, you are right, my answer is not complete and bulletproof and I'm sorry for sarcastic comment.
lubos hasko
+1  A: 

Programmatically you'd get the starting image name using Win32 API like NtQueryInformationProcess, or in .Net use System.Diagnostics.Process.GetProcesses() and read Process.StartInfo.FileName.

Then open and decode the PE headers of that image using details prescribed in the MSDN article below:

http://msdn.microsoft.com/en-us/magazine/cc301808.aspx

Caveats: will only detect .NET built assemblies e.g. won't detect Win32 EXEs dynamically hosting CLR using CorHost APIs.

stephbu
+6  A: 

There's a trick I once learned from Scott Hanselman's list of interview questions. You can easily list all programs running .NET in command prompt by using:

tasklist /m "mscor*"

It will list all processes that have mscor* amongst their loaded modules.

We can apply the same method in code:

public static bool IsDotNetProcess(this Process process)
{
  var modules = process.Modules.Cast<ProcessModule>().Where(
      m => m.ModuleName.StartsWith("mscor", StringComparison.InvariantCultureIgnoreCase));

  return modules.Count() > 0;
}
hmemcpy
Note this does leave out possible Mono processes.
Dykam
@Dykam Isn't mono's runtime also called mscorlib.dll ?
hmemcpy
The runtime is just `mono`. Or `mono.exe` on windows. .Net uses PE to let the OS use mscorlib.dll to start the app, but mono doesn't do such a trick. And the real core lib is called corlib.dll I think, as it isn't MS's corlib.
Dykam
Interesting... thanks :)
hmemcpy
I don't think this will work anymore for .NET 4.0, the DLLs were renamed. You'll also get false positives for apps that host the CLR, Visual Studio for example.
Hans Passant
The .NET 4.0 runtime is called clr.dll.
Brian Rasmussen
+1  A: 

Use the CLR COM interfaces ICorPublish and ICorPublishProcess. The easiest way to do this from C# is to borrow some code from SharpDevelop's debugger, and do the following:

ICorPublish publish = new ICorPublish();
ICorPublishProcess process;

process = publish.GetProcess(PidToCheck);

if (process == null || !process.IsManaged)
{
    // Not managed.
}

// Managed.
wj32
A: 

I suggest downloading the Redgate's DotNetReflector and checking if it can open the application.

Tamir