Using LINQ to update string array

前端 未结 3 1551
庸人自扰
庸人自扰 2021-01-18 23:18

I\'m trying to create a method to update an AssemblyInfo file with a new version string, using LINQ. I can successfully extract the string I need to update, but am not sure

3条回答
  •  抹茶落季
    2021-01-18 23:46

    I suggest using Regex for this:

    private static void UpdateVersion(string file, string version)
    {
        var fileContent = File.ReadAllText(file);
        var newFileContent = Regex.Replace(
            fileContent,
            @"(?<=AssemblyVersion\("")(?.*?)(?=""\))",
            version);
        File.WriteAllText(file, newFileContent);
    }
    

    You can still do this with LINQ, but this will be less efficient and more error-prone, I guess.

    private static void UpdateVersion(string file, string version)
    {
        var linesList = File.ReadAllLines(file).ToList();
        var line = linesList.Single(x => x.Trim().StartsWith("[assembly: AssemblyVersion"));
        linesList.Remove(line);
        linesList.Add("[assembly: AssemblyVersion(\"" + version + "\")]");
        File.WriteAllLines(file, linesList.ToArray());
    }
    

提交回复
热议问题