【发布时间】:2021-04-11 05:17:16
【问题描述】:
我已经创建了 UWP 应用程序。我使用了一些仅在 UWP 的最新版本(19041、17763)中可用的 API。我想在以前的版本和最新版本中运行。因此,如果我以编程方式获取应用程序目标版本,我将检查使应用程序与每个版本兼容的条件。是否可以获取应用程序的目标版本。
【问题讨论】:
我已经创建了 UWP 应用程序。我使用了一些仅在 UWP 的最新版本(19041、17763)中可用的 API。我想在以前的版本和最新版本中运行。因此,如果我以编程方式获取应用程序目标版本,我将检查使应用程序与每个版本兼容的条件。是否可以获取应用程序的目标版本。
【问题讨论】:
您可以在应用安装文件夹中获取 AppxManifest.xml 文件。之后,您可以使用Windows.Data.Xml.Dom.XmlDocument Class 加载xml 文件。在 AppxManifest.xml 中,您可以在 Package->Dependencies 下找到一个名为 TargetDeviceFamily 的节点,它包含一个名为 MaxVersionTested 是目标版本的值。
这是您可以检查的代码 sn-p:
var file = await Package.Current.InstalledLocation.GetFileAsync("AppxManifest.xml");
var xmlDocument = await XmlDocument.LoadFromFileAsync(file);
var VersionText = xmlDocument.ChildNodes.LastOrDefault().ChildNodes.Where(p => p.NodeName == "Dependencies").FirstOrDefault().ChildNodes.Where(t => t.NodeName == "TargetDeviceFamily").FirstOrDefault().Attributes.GetNamedItem("MaxVersionTested").InnerText;
MyTextBlock.Text = VersionText;
【讨论】:
您可以使用 powershell 命令从文件元数据中获取版本(您必须确保您的产品在此处具有有效值)
然后您可以使用以下逻辑: 在路径参数上发送路径到带有文件元数据更新字段的应用程序可执行文件(或 dll)。
string GetVersion(string path)
{
var command = $"(Get-Command \"{path}\").FileVersionInfo.ProductVersion";
var processStartInfo = new ProcessStartInfo
{
FileName = "cli",
Arguments = $"/c powershell {command}",
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
UseShellExecute = false
};
var p = System.Diagnostics.Process.Start(proc);
p.WaitForExit();
var fileVersion = p.StandardOutput.ReadToEnd();
return fileVersion;
}
此解决方案适用于本地和远程目标..
如果您仅在本地需要它,您可以简单地使用 FileVersionInfo 类并将其从 FileVersion 属性中取出
如 MSDN 示例中给出的:
public static void Main(string[] args)
{
// Get the file version for the notepad.
// Use either of the two following commands.
FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe"));
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);
}
您可以在此处阅读更多内容: https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.fileversioninfo?view=net-5.0
【讨论】: