我创建了一个代码来获取目录名的版本号,例如这个名为Update5.0.1的文件夹我只需要“5.0.1”部分。我将目录路径传递给此函数:
public int CompareVersion(string NovoUpdate, string Config)
{
int Status = 0;
try
{
ExeConfigurationFileMap configOld = new ExeConfigurationFileMap();
configOld.ExeConfigFilename = Config;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configOld, ConfigurationUserLevel.None);
if (config.AppSettings.Settings["Version"] != null)
{
string value = config.AppSettings.Settings["Version"].Value.ToString();
Version ver = Version.Parse(value);
Version version = null;
Version VersionFinal = null;
var lastVersion = new DirectoryInfo(NovoUpdate).FullName;
//.Where(d => d.Name.StartsWith("UPDATE_"))
.Select(d => new { Directory = d, Token = d.Name.Split('_') })
.Where(x => x.Token.Length == 3 && Version.TryParse(x.Token[2], out version))
.Select(x => new { x.Directory, Date = x.Token[1], Version = version })
.OrderByDescending(x => x.Version)
.FirstOrDefault();
if (lastVersion != null)
{
VersionFinal = Version.Parse(lastVersion.ToString());
}
if (ver >= VersionFinal)
Status = 1;
else
Status = 0;
}
else Status = -1;
}
catch (Exception ex)
{
Erro NovoErro = new Erro();
Program.Erro = ex.ToString();
NovoErro.ShowDialog();
}
return Status;
}
我在这一行有错误:
var lastVersion = new DirectoryInfo(NovoUpdate);
//.Where(d => d.Name.StartsWith("UPDATE_"))
.Select(d => new { Directory = d, Token = d.Name.Split('_') })
我已经尝试将“lastVersion”更改为字符串或只是使用 “NovoUpdate”字符串而不是DirectoryInfo。我真的不知道 如何使用linq任何帮助都是aprecciated。
答案 0 :(得分:0)
我想你忘了打电话给#34; GetDirectories "方法,如:
new DirectoryInfo(NovoUpdate).GetDirectories().Select...
答案 1 :(得分:0)
如果您只想从目录名称中提取版本,则不需要Linq。
尝试
string path = @"C:\Path\Update5.0.1";
string name = System.IO.Path.GetFileName(path);
string match = System.Text.RegularExpressions.Regex.Match(name, @"\d\.\d\.\d");
string version = match.Value;
您将获得" 5.0.1"
答案 2 :(得分:0)
以下是最终完整工作的代码:
public int CompareVersion(string NovoUpdate, string Config, bool ServiceChanged)
{
Global.Erro = "";
Global.ErroGrave = false;
int Status = 0;
ExeConfigurationFileMap configOld = new ExeConfigurationFileMap();
configOld.ExeConfigFilename = Config;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configOld, ConfigurationUserLevel.None);
if (config.AppSettings.Settings["Version"] != null)
{
string value = config.AppSettings.Settings["Version"].Value.ToString();
Version ver = Version.Parse(value);
Version versione = null;
if (System.IO.Path.GetFileName(NovoUpdate).ToLower() == "orcaservice")
{
string name2 = Directory.GetParent(NovoUpdate).ToString();
string Versionn = System.IO.Path.GetFileName(name2);
string[] Versions2 = Versionn.Split('_');
Version.TryParse(Versions2[2], out versione);
}
else
{
}
if (ver < versione)
Status = 1;
else
Status = 0;
}
else Status = -1;
return Status;
}