Nice programing

파일 경로에서 .exe 파일 버전 번호를 얻는 방법

nicepro 2020. 11. 22. 20:34
반응형

파일 경로에서 .exe 파일 버전 번호를 얻는 방법


C #의 코드와 함께 .Net 3.5 / 4.0을 사용하고 있습니다.

내 C : 드라이브에있는 exe 파일의 버전 번호를 얻으려고합니다.

예를 들어 경로는 c : \ Program \ demo.exe입니다. demo.exe의 버전 번호가 1.0.

이 경로를 사용하여 버전 번호를 얻으려면 어떻게해야합니까?.


FileVersionInfo.ProductVersion사용 하여 경로에서이를 가져올 수 있습니다 .

var versionInfo = FileVersionInfo.GetVersionInfo(pathToExe);
string version = versionInfo.ProductVersion; // Will typically return "1.0.0" in your case

2018 년 업데이트 및 현대화 (예 : C # 6의 문자열 보간) :

허용되는 답변은 부분적으로 정확하지 않으며 (ProductVersion은 일반적으로 세 부분으로 구성된 버전을 반환하지 않음) 약간 오해의 소지가 있습니다.

여기에 더 완전한 답변이 있습니다. 너무 길지 않은 본문을 얻기 위해 많은 사람들에게 "충분할"수있는 짧은 요약으로 나누었습니다. 자세한 두 번째 부분을 읽을 의무는 없으므로 tl; dr :-)

짧은 요약:

  1. 각 파일에는 다른 버전 (어셈블리 버전, 파일 버전, 제품 버전)이 있지만 일반적 으로 파일 수준에서 이미 "버전 지옥"을 얻지 못하도록 모두 동일하게 설정합니다 (충분히 일찍 올 것입니다).

  2. 파일 버전 (익스플로러에 표시되고 설정 / 설치에 사용됨)은 내가 가장 신경 쓰는 데 가장 중요한 이름입니다.

  3. 이를 위해서는 AssemblyInfo.cs 파일의 fileversion 을 아래와 같이 주석 처리하면 됩니다. 이렇게하면 한 파일의 가능한 세 가지 버전이 동일합니다!

    [assembly : AssemblyVersion ( "1.1.2. ")]
    // [assembly : AssemblyFileVersion ( "1.1.2.
    ")]

  4. 예를 들어 시맨틱 버전 관리의 경우 가능한 4에서 3 개의 버전 부분 만 가져 오려고합니다.

모든 Visual Studio 빌드에 대한 자동 빌드 계산 기능이 있으면 유용합니다. 그러나이 빌드 카운팅은 내부 또는 외부 고객에게 항상 유용한 것은 아닙니다. 따라서 Windows에 파일 버전을 언급하기 위해 제목 대화 상자에서 v1.2.3의 세 부분 만 표시하는 것이 좋습니다 (물론 시맨틱 버전 관리 포함).

using System.Diagnostics;
...

var versInfo= FileVersionInfo.GetVersionInfo(pathToVersionedFile); 
string fileVersionFull = versInfo.FileVersion; // No difference here for versinfo.ProductVersion if recommendation in AssemblyInfo.cs is followed
string fileVersionSemantic = $"V{versInfo.FileMajorPart}.{versInfo.FileMinorPart}.{versInfo.FileBuildPart}";
string fileVersionFull2 =    $"V{versInfo.FileMajorPart}.{versInfo.FileMinorPart}.{versInfo.FileBuildPart}.{versInfo.FilePrivatePart}";

FileVersionFull2는 그냥 같은 들어있는 "V"를 제외한 모든 4 개 부분을 처리하는 방법을 보여주고있다 FileVersionFull .

세부 사항 :

첫 번째는 세 가지 버전을 가져오고 설정하는 방법에 대한 치트 시트입니다.

파일 버전 : [assembly : AssemblyFileVersion (..)] => System.Diagnostics.FileVersionInfo.FileVersion

제품 버전 : [assembly : AssemblyInformationalVersion (..)] => System.Diagnostics.FileVersionInfo.ProductVersion

어셈블리 버전 : [assembly : AssemblyVersion (..)] => System.Reflection.Assembly.Version

특히 기본값 설정은 혼란 스러울 수 있습니다. 세부 정보를 이해하기위한 권장 SO 링크 : FileVersionInfo 및 AssemblyInfo

EntryAssembly vs. ExecutingAssembly 실행
중인 앱의 버전을 가져 오는 모든 경우를 완전히 고려하려면 다른 곳에서 자세한 내용을 검색하십시오. 예 : 어셈블리 위치를 가져 오는 데 더 적합합니다. GetAssembly (). Location 또는 GetExecutingAssembly (). Location
특히 다음과 같이 할 수 있습니다. EntryAssembly 또는 ExecutingAssembly를 사용해야하는 경우 혼동 될 수 있습니다. 둘 다 장점과주의 사항이 있습니다. 예를 들어 도우미 어셈블리와 같이 .exe와 동일한 어셈블리에 다음 코드가 없으면 상황이 더 복잡해집니다. 일반적으로 EntryAssembly를 사용하여 .exe 버전을 가져옵니다.
그러나 : Visual Studio의 단위 테스트에서 병렬 .exe 프로젝트에서 루틴을 테스트하려면 GetEntryAssembly ()가 작동하지 않습니다 (내 환경 : NUnit, VS2017). 그러나 GetExecutingAssembly ()는 적어도 단위 테스트 중에 만 테스트 프로젝트의 어셈블리 버전을 얻습니다. 나에게 충분하다. 간단하지 않은 상황이있을 수있다.
원한다면 선언을 정적으로 생략하여 하나의 프로그램에서 여러 다른 어셈블리의 버전을 가져올 수 있습니다.

public static class AppInfo
{
  public static string FullAssemblyName { get; }
  ..

  static AppInfo()
  {
      Assembly thisAssembly = null;
      try
      {
          thisAssembly = Assembly.GetEntryAssembly();
      }
      finally
      {
          if (thisAssembly is null)
              thisAssembly = Assembly.GetExecutingAssembly();
      }
      FullAssemblyName = thisAssembly.Location;
      var versInfo = FileVersionInfo.GetVersionInfo(FullAssemblyName);
      ..
  }
}

Product version vs. file version:
ProductVersion of a file is shown in Windows Explorer too. I would recommend to maximally differentiate ProductVersion and FileVersion in the most "customer-visible" file (mostly the main .exe of application). But it could be of course a choice to differentiate for every file of the "main" app and let them all have them all the "marketing" ProductVersion which is seen by customer. But experience shows that it is neither necessary nor cheap to try to synchronize technical versions and marketing versions too much. Confusion doesn´t decrease really, costs increase. So the solution described in the first part here should do it mostly.

History: Assembly version vs. file version: One reason for having different versions is also that one .NET assembly can originally consist of several files (modules)- theoretically. This is not used by Visual Studio and very seldom used elsewhere. This maybe one historical reason of giving the possibility to differentiate these two versions. Technically the assembly version is relevant for .NET related versioning as GAC and Side-by-side versions, the file version is more relevant for classic setups, e.g. overwriting during updates or for shared files.


In the accepted answer a reference is made to "pathToExe".

This path can be retrieved and used as follows:

var assembly = Assembly.GetExecutingAssembly();
var fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
var version = fvi.FileVersion; // or fvi.ProductVersion

Hope this saves someone from doing some unnecessary extra steps.


Where Program is your class name:

Console.WriteLine("Version = " + typeof(Program).Assembly.GetName().Version.ToString()) ;

I'm not sure if this is what you are looking for, but:

http://www.daniweb.com/software-development/csharp/threads/276174/c-code-to-get-dll-version

It says,

// Get the file version info for the notepad.
FileVersionInfo myFileVersionInfo =  FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\notepad.exe");

// Print the file name and version number.
Console.WriteLine("File: " + myFileVersionInfo.FileDescription + '\n' + "Version number: " + myFileVersionInfo.FileVersion);

Use, it work:

using System.Reflection;

string v = AssemblyName.GetAssemblyName("Path/filename.exe").Version.ToString();

//Example your file version is 1.0.0.0
//Solution 1
Dim fileVer As FileVersionInfo = FileVersionInfo.GetVersionInfo(Environment.CurrentDirectory + "\yourExe.exe")
yourLabel.Text = fileVer.FileVersion
//Solution 2
//Get File Version Number
yourLabel.Text = Application.ProductVersion
//Both solution will get output 1.0.0.0

참고URL : https://stackoverflow.com/questions/11350008/how-to-get-exe-file-version-number-from-file-path

반응형