C# 从 AssemblyInfo.cs 获取程序集版本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15126113/
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 14:08:04  来源:igfitidea点击:

Getting Assembly Version from AssemblyInfo.cs

c#asp.net-mvcassemblyinfo

提问by Tarik

We have an AssemblyInfo.csfile in our Web Application but we do have other projects in the same solution. They are mostly class libraries. I am told to display Assembly Version from AssemblyInfo.cson our UI. I've found the following solution in SO from C# AssemblyFileVersion usage within a program

我们AssemblyInfo.cs的 Web 应用程序中有一个文件,但我们在同一解决方案中有其他项目。它们主要是类库。我被告知AssemblyInfo.cs在我们的 UI 上显示程序集版本。我从程序中的C# AssemblyFileVersion 使用中找到了以下解决方案

using System.Reflection;
Version version = Assembly.GetExecutingAssembly().GetName().Version;

or

或者

using System.Reflection;
using System.IO;

FileVersionInfo fv = System.Diagnostics.FileVersionInfo.GetVersionInfo
                               (Assembly.GetExecutingAssembly().Location);

Console.WriteLine("AssemblyVersion : {0}", 
         Assembly.GetExecutingAssembly().GetName().Version.ToString());

Console.WriteLine ("AssemblyFileVersion : {0}" , 
         fv.FileVersion.ToString ());

But this confuses me little bit. It says GetExecutingAssembly()and what if it is running on another assembly from other class libraries? Will those codes fetch from AssemblyInfo.csfile that is residing in the Web Project all the time? (which is what I want)

但这让我有点困惑。它说GetExecutingAssembly()如果它在来自其他类库的另一个程序集上运行怎么办?这些代码会一直从AssemblyInfo.cs驻留在 Web 项目中的文件中获取吗?(这是我想要的)

采纳答案by SLaks

As the documentation states, Assembly.GetExecutingAssembly()gets the assembly that the calling code was compiled inside of.

正如文档所述,Assembly.GetExecutingAssembly()获取调用代码在其中编译的程序集。

If you want to be more explicit (and faster), you can write typeof(SomeType).Assembly, where SomeTypeis any type in the project you're looking for.

如果您想更明确(和更快),您可以编写typeof(SomeType).Assembly, where SomeTypeis any type in the project you are looking for.

回答by Mhd

if you want read file then you can do this.

如果你想读取文件,那么你可以这样做。

string path = @"d:\AssemblyInfo.cs";
        if (File.Exists(path))
        {
            // Open the file to read from.
            string[] readText = File.ReadAllLines(path);
            var versionInfoLines = readText.Where(t => t.Contains("[assembly: AssemblyVersion"));
            foreach (string item in versionInfoLines)
            {
                string version = item.Substring(item.IndexOf('(') + 2, item.LastIndexOf(')') - item.IndexOf('(') - 3);          
                Console.WriteLine(version);
            }

        }

Output

输出

1.0.0.0