我试图通过名称获取进程记事本,但获得异常IndexOutOfRangeException

时间:2014-06-02 19:08:55

标签: c# winforms

获取异常IndexOutOfRangeException 我怎么解决呢? 是什么原因造成的?

public partial class Form1 : Form
{
   const int PROCESS_WM_READ = 0x0010;

   [DllImport("kernel32.dll")]
   public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

   [DllImport("kernel32.dll")]
   public static extern bool ReadProcessMemory(int hProcess,
      int lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);

   public Form1()
   {
      InitializeComponent();

      Process process = Process.GetProcessesByName("notepad")[0];
   }
}

为什么我会收到此异常?

索引超出了数组的范围

System.IndexOutOfRangeException was unhandled
  HResult=-2146233080
  Message=Index was outside the bounds of the array.
  Source=Read
  StackTrace:
       at Read
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

1 个答案:

答案 0 :(得分:2)

那是因为GetProcessesByName没有返回任何结果;索引0没有对象。这意味着它没有找到流程notepad