如何在 C# 代码中获取当前项目名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18316683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:54:03  来源:igfitidea点击:

How to get the current project name in C# code?

c#asp.netexception

提问by J - C Sharper

I want to send an email to myself when an exception is thrown. Using StackFrame object, I am able to get File Name, Class Name and even class method that throw the Exception, but I also need to know the project name as many of my ASP.NET project has the same file name, class name and method.

我想在抛出异常时给自己发送一封电子邮件。使用 StackFrame 对象,我能够获得抛出异常的文件名、类名甚至类方法,但我还需要知道项目名称,因为我的许多 ASP.NET 项目具有相同的文件名、类名和方法.

This is my code:

这是我的代码:

    public static string JndGetEmailTextForDebuggingExceptionError(this Exception Ex)
    {
        StackFrame sf = Ex.JndGetStackFrame();

        string OutputHTML =         "<i><b><u>For Developer Use Only: </u></b></i>"                                                 + "<br>" + 
                                                                                                                                      "<br>" +
                                    "Project Name:   "  + HttpContext.Current.ApplicationInstance.GetType().Assembly.GetName().Name + "<br>" + //Under discussion
                                    "File Name:      "  + sf.GetFileName()                                                          + "<br>" +
                                    "Class Name:     "  + sf.GetMethod().DeclaringType                                              + "<br>" +
                                    "Method Name:    "  + sf.GetMethod()                                                            + "<br>" +
                                    "Line Number:    "  + sf.GetFileLineNumber()                                                    + "<br>" +
                                    "Line Column:    "  + sf.GetFileColumnNumber()                                                  + "<br>" +
                                    "Error Message:  "  + Ex.Message                                                                + "<br>" +
                                    "Inner Message : "  + Ex.InnerException.Message                                                 + "<br>";

        return OutputHTML;
    }

Thanks ALL.

谢谢大家。

采纳答案by Tim S.

You can use Assembly.GetCallingAssemblyif you have your logging code in a separate library assembly, and call directly from your ASP.NET assembly to your library, and you mark the method so that it won't be inlined:

您可以使用Assembly.GetCallingAssembly,如果你在一个单独的图书馆有你的日志代码组装和装配直接从你的ASP.NET打电话给你的资料库,以及标记方法,这样就不会被内联:

[MethodImpl(MethodImplOptions.NoInlining)]
public static string JndGetEmailTextForDebuggingExceptionError(this Exception Ex)
{
    StackFrame sf = Ex.JndGetStackFrame();

    string OutputHTML =         "<i><b><u>For Developer Use Only: </u></b></i>"                    + "<br>" + 
                                                                                                     "<br>" +
                                "Project Name:   "  + Assembly.GetCallingAssembly().GetName().Name + "<br>" +
                                "File Name:      "  + sf.GetFileName()                             + "<br>" +
                                "Class Name:     "  + sf.GetMethod().DeclaringType                 + "<br>" +
                                "Method Name:    "  + sf.GetMethod()                               + "<br>" +
                                "Line Number:    "  + sf.GetFileLineNumber()                       + "<br>" +
                                "Line Column:    "  + sf.GetFileColumnNumber()                     + "<br>" +
                                "Error Message:  "  + Ex.Message                                   + "<br>" +
                                "Inner Message : "  + Ex.InnerException.Message                    + "<br>";

    return OutputHTML;
}

On any entry points in your library that can end up wanting to log the project name, you'd have to record the calling assembly and mark it NoInlining, then pass that around internally.

在您的库中可能最终想要记录项目名称的任何入口点上,您必须记录调用程序集并标记它NoInlining,然后在内部传递它。

If you're using .NET 4.5, there's an alternative way to do this: CallerFilePath. It has the same restrictions on entry points, and it returns the source path on your machine instead of the assembly name (which is probably less useful), but it's easier to know that it'll work (because it compiles it, just like optional parameters are compiled in), and it allows inlining:

如果您使用的是 .NET 4.5,则有一种替代方法可以做到这一点:CallerFilePath. 它对入口点有同样的限制,它返回你机器上的源路径而不是程序集名称(这可能不太有用),但更容易知道它会工作(因为它编译它,就像可选的参数被编译在)中,并且它允许内联:

public static string JndGetEmailTextForDebuggingExceptionError
              (this Exception Ex, [CallerFilePath] string filePath = "")
{
    StackFrame sf = Ex.JndGetStackFrame();

    string OutputHTML =         "<i><b><u>For Developer Use Only: </u></b></i>" + "<br><br>" +
                                "Source File Path:   "  + filePath + "<br>" +
...

回答by SLaks

You can use

您可以使用

HttpContext.Current.ApplicationInstance.GetType().Assembly.GetName().Name

If this returns App_global.asax...., change it to

如果返回App_global.asax....,请将其更改为

HttpContext.Current.ApplicationInstance.GetType().BaseType.Assembly.GetName().Name

If you aren't running in an HTTP request, you will need some way to get ahold of the HttpContext.

如果您没有在 HTTP 请求中运行,您将需要某种方式来获取HttpContext.

This will return different results if you're in a Web Site project (as opposed to Web Application).

如果您在网站项目中(与 Web 应用程序相反),这将返回不同的结果。

You can also use HttpRuntime.AppDomainAppPathto get the physical path on disk to the deployed site; this will work everywhere.

您还可以使用HttpRuntime.AppDomainAppPath获取磁盘上到已部署站点的物理路径;这将适用于任何地方。

回答by Ramesh Rajendran

Reflection is the best way to find out product name,company name version like information.

反射是找出产品名称、公司名称版本等信息的最佳方式。

public static string ProductName
{
 get
 {
    AssemblyProductAttribute myProduct =(AssemblyProductAttribute)AssemblyProductAttribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
     typeof(AssemblyProductAttribute));
      return myProduct.Product;
  }
}

And Another way like get direct project name

还有另一种方式,比如直接获取项目名称

string projectName=System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();

回答by DGibbs

This ought to be enough

这应该足够了

string projectName = Assembly.GetCallingAssembly().GetName().Name;

Edit* If you are running this from another assembly then you should use GetCallingAssemblyinstead.

编辑* 如果您从另一个程序集运行它,那么您应该改用GetCallingAssembly

回答by pipding

For anyone looking for an ASP.NET Core compatible solution, the following should work;

对于任何寻找 ASP.NET Core 兼容解决方案的人来说,以下应该有效;

System.Reflection.Assembly.GetEntryAssembly().GetName().Name


.NET Core API Reference


.NET Core API 参考