在Application Exit上指定返回错误代码

时间:2010-07-08 15:01:08

标签: c# exit-code

如何在应用程序退出时指定返回错误代码?如果这是一个VC ++应用程序,我可以使用SetLastError(ERROR_ACCESS_DENIED) - return GetLastError() API。有没有办法在C#中做到这一点?

  static int Main(string[] args)
  {
     Tool.Args = args;

     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Download_Tool());

     return Tool.ErrorCode;
  }

如何设置Tool.ErrorCode值可理解?如果我尝试像Tool.ErrorCode = ERROR_ACCESS_DENIED这样的东西,我会收到一个错误,“当前上下文中不存在名称ERROR_ACCESS_DENIED。”感谢。

其他信息

我的例子过于简化了。有没有办法这样的事情:

Tool.ErrorCode = ERROR_ACCESS_DENIED;
return Tool.ErrorCode;

...生成编译错误,而不是:

Tool.ErrorCode = 5;
return Tool.ErrorCode;

......哪个有效,但使用的是“幻数”。我想避免使用魔法数字。

2 个答案:

答案 0 :(得分:9)

http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx

Environment.Exit(exitCode)

<强>更新

您收到“ERROR_ACCESS_DENIED”编译错误的原因是您尚未定义它。您需要自己定义:

const int ERROR_ACCESS_DENIED = 5;

然后你可以使用:

Environment.Exit(ERROR_ACCESS_DENIED)

更新2

如果您正在为C#需求寻找一套现成的winerror.h常量,那么它就是:

http://www.pinvoke.net/default.aspx/Constants/WINERROR.html

我可能会修改GetErrorName(...)方法来进行一些缓存,例如:

private static Dictionary<int, string> _FieldLookup;

public static bool TryGetErrorName(int result, out string errorName)
{
    if (_FieldLookup == null)
    {
        Dictionary<int, string> tmpLookup = new Dictionary<int, string>();

        FieldInfo[] fields = typeof(ResultWin32).GetFields();

        foreach (FieldInfo field in fields)
        {
            int errorCode = (int)field.GetValue(null);

            tmpLookup.Add(errorCode, field.Name);
        }

        _FieldLookup = tmpLookup;
    }

    return _FieldLookup.TryGetValue(result, out errorName);
}

答案 1 :(得分:-2)

设置Environment.ExitCode

static void Main(string[] args)
  {
     Tool.Args = args;

     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Download_Tool());

     Environment.ExitCode = Tool.ErrorCode;
  }

请参阅MSDN - Environment.ExitCode Property