C# 检查是否安装了 Java && version(int)

标签 c#

我正在为我的 java 游戏制作启动器,我想检查是否安装了 java 8,因为如果没有安装 java 则无法运行 java 应用程序。我在互联网上查看了答案,但找不到我的问题的答案。

我的当前代码:

string temp = GetJavaVersion();
string temp2 = temp.Substring(13, temp.Length - 13);
//string temp3 = temp2.Substring(10, temp2.Length - 1);
string installPath = temp2;
ShowMessageBox(installPath, "Debug", MessageBoxButtons.OK, 
MessageBoxIcon.Information);

GetJavaVersion()方法代码:

        try
        {
            ProcessStartInfo procStartInfo =
                new ProcessStartInfo("java", "-version ");

            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.RedirectStandardError = true;
            procStartInfo.UseShellExecute = false;
            procStartInfo.CreateNoWindow = true;
            Process proc = new Process();
            proc.StartInfo = procStartInfo;
            proc.Start();
            return proc.StandardError.ReadLine();

        }
        catch (Exception objException)
        {
            return null;
        }

输出:

"1.8.0_144"

问题是我得到引号和不必要的数字。(我只需要数字 8 来指示安装了 java 版本 8),如果没有安装 java 则只输出 0。

有人可以帮忙吗?

编辑 如果我使用 Regex 那么我如何将数字获取到 int 变量? 代码:

   string temp = GetJavaVersion();
   string temp2 = temp.Substring(13, temp.Length - 13);
   requiredJavaVersion = 8;
   //string temp3 = temp2.Substring(10, temp2.Length - 1);
   string regexPattern = @"([0-9]+)";
   Regex regex = new Regex(regexPattern);
   //Error comes here
   int currentVersion = Convert.ToInt32(regex.Matches("1.8.0_144")[1]); 

   if (currentVersion == requiredJavaVersion)
   {
       hasRequiredVersion = true;
   }

最佳答案

您可以使用正则表达式将您的版本分解为数字:

string regexPattern = @"([0-9]+)";
Regex regex = new Regex(regexPattern);

这将返回一个包含 4 个结果的数组:

1 8 0 144

然后获取您的 8 版本,如 regex.Matches("1.8.0_144")[1].Value;

要将其转换为int,请使用

int value = int.Parse(regex.Matches("1.8.0_144")[1].Value);

关于C# 检查是否安装了 Java && version(int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46038539/

相关文章:

c# - 检查以字节为单位的图像文件大小

c# - ASP.NET 核心 : [FromQuery] usage and URL format

c# - Android System.DateTime.now 的 Unity 系统时间不起作用?

c# - DataGridView、BindingSource、DataMember - 我不明白

c# - 如何在主容器中注册类型,但在子容器中解析?

c# - 在请求之间创建一个托管在 IIS7 中的 WCF 服务吗?

c# - 如何在 NHibernate ByCode 中分别映射相同类型的两个组件属性?

c# - 希望对自动化软件安装项目提出建议

c# - 使用 StreamWriter 追加文本

c# - jquery 调用页面方法失败