title: How can I run an ANY CPU .NET executable programmatically in either 32-bit or 64-bit configurations?
body: <p>I have a C# application that is built to run on both 32-bit and 64-bit processors. I am attempting to enumerate the modules of all processes on a given system and this becomes problematic when trying to enumerate 32-bit process modules from a 64-bit application; Windows or .NET prohibits it.</p>
  
  <p>I thought it would be pretty cool if I could re-launch the application from within itself, but force it to run as 32-bit, and then it would correctly enumerate the process modules it missed on the last run.</p>
  
  <p>How can I run an executable programmatically and indicate that even though it was built with an <code>ANY CPU</code> configuration, it should run as a 32-bit process?</p>
  
  <p>The code below throws a <code>System.ComponentModel.Win32Exception</code> with the text "A 32 bit processes cannot access modules of a 64 bit process."</p>
  
  <pre><code>[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
  [return: MarshalAs(UnmanagedType.Bool)]
  private static extern bool IsWow64Process(
       [In] IntPtr hProcess,
       [Out] out bool lpSystemInfo);
  
  private static void Main()
  {
    Process[] processes = Process.GetProcesses();
  
    using (FileStream fileStream = new FileStream("ProcessModulesDump.dat", FileMode.Create, FileAccess.Write, FileShare.None))
    {
        using (GZipStream gzipStream = new GZipStream(fileStream, CompressionLevel.Optimal))
        {
            using (TextWriter writer = new StreamWriter(gzipStream))
            {
                foreach (Process process in processes)
                {
                    writer.WriteLine("{0} - {1}", process.Id, process.ProcessName);
  
                    //bool lpSystemInfo;
                    //if ((Environment.Is64BitProcess &amp;&amp; 
                           IsWow64Process(process.Handle, out lpSystemInfo)) ||
                           (!Environment.Is64BitProcess &amp;&amp;
                            !IsWow64Process(process.Handle, out lpSystemInfo)))
                    //{
                        foreach (ProcessModule module in process.Modules)
                        {
                            writer.WriteLine("\t{0} - {1} ({2})", 
                                module.BaseAddress, 
                                module.ModuleName, 
                                module.FileName);
                        }
                    //}
                }
            }
        }
    }
  }
  </code></pre>