简体   繁体   English

Mono / MonoDevelop:在运行时获取解决方案版本

[英]Mono / MonoDevelop: Get solution version at runtime

I am looking to retrieve the application version (essentially the <ReleaseVersion> property in the solution file) at runtime. 我希望在运行时检索应用程序版本(本质上是解决方案文件中的<ReleaseVersion>属性)。 How does one access this via code? 一个人如何通过代码访问它?

The standard way of setting the application version in .NET (and therefore presumably MONO) is to use the AssemblyVersion attribute. 在.NET(因此可能是MONO)中设置应用程序版本的标准方法是使用AssemblyVersion属性。 This is normally specified in the AssemblyInfo.cs file, but can be specified in other files, as is shown below. 这通常在AssemblyInfo.cs文件中指定,但可以在其他文件中指定,如下所示。

To get the version at runtime, you can use the AssemblyName.Version property . 要在运行时获取版本,可以使用AssemblyName.Version属性 The following is a slightly modified version of the code from the given link: 以下是来自给定链接的代码的略微修改版本:

using System;
using System.Reflection;

[assembly:AssemblyVersion("1.1.0.0")]

class Example
{
    static void Main()
    {
        Console.WriteLine("The version of the currently executing assembly is: {0}",
          Assembly.GetExecutingAssembly().GetName().Version);
    }
}

When compiled and run, it produces this: 编译并运行后,它会产生以下结果:

The version of the currently executing assembly is: 1.1.0.0 当前正在执行的程序集的版本是:1.1.0.0

The above was tested on both .NET (Visual Studio 2010), and Mono 3.0 (compiled using mcs from the command line, not Mono Develop). 上面的代码在.NET(Visual Studio 2010)和Mono 3.0(使用mcs从命令行而不是Mono Develop编译)上进行了测试。

您是否尝试过使用本论坛中的建议-> 获取最新版本

It's an ugly hack, but you can utilise the BeforeBuild target to write that property to a file, which you then promptly include as an embedded resource. 这是一个丑陋的hack,但是您可以利用BeforeBuild目标将该属性写入文件,然后将其立即作为嵌入式资源包括在内。 In your *.csproj file: 在您的* .csproj文件中:

<ItemGroup>
    <EmbeddedResource Include="release-version.txt" />
</ItemGroup>

<!-- .... -->

<Target Name="BeforeBuild">
    <Exec WorkingDirectory="$(ProjectDir)" Command="echo $(ReleaseVersion) &gt;release-version.txt" />
</Target>

....then in your C♯ code, you could create a property like this: ....然后在您的C♯代码中,您可以创建如下属性:

public static string Version {
    get {
        using (StreamReader resourceReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("SBRL.GlidingSquirrel.release-version.txt")))
        {
            return resourceReader.ReadToEnd().Trim();
        }
    }
}

This should work on all major operating systems. 这应该适用于所有主要操作系统。 Don't forget: 不要忘记:

  • To add using System.Reflection; using System.Reflection;添加using System.Reflection; to the top of your file if you haven't already 如果还没有的话
  • To add the release-version.txt file to your version control's ignore list (eg .gitignore , etc.) 要将release-version.txt文件添加到版本控件的忽略列表(例如.gitignore等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM