2014-07-22 72 views
-1

我想增加版本的最後編號(例如:1.0.0.0 - > 1.0.0.1)。 我寧願白馬這段代碼:)C#「Version-Updater」

的實際工作中的代碼看起來像這樣:

private void UpdateApplicationVersion(string filepath) 
    { 
     string currentApplicationVersion = "1.2.3.4" 
     string newApplicationVersionDigit = ((currentApplicationVersion.Split('.')[3]) + 1).ToString(); 


     string newApplicatonVersion = string.Empty; 

     for (int i = 0; i <= currentApplicationVersion.Length; i++) 
     { 
      if (i == 7) 
      { 
       newApplicatonVersion += newApplicationVersionDigit ; 
      } 
      else 
      { 
       newApplicatonVersion += currentApplicationVersion.ToCharArray()[i]; 
      } 

     } 

回答

1

我認爲這可以通過解析所有的c版本的組成部分,操縱最後一個,然後再將它們放在一起,如下所示。

string[] Components = currentApplicationVersion.Split('.'); 
int Maj = Convert.ToInt32(Components[0]); 
int Min = Convert.ToInt32(Components[1]); 
int Revision = Convert.ToInt32(Components[2]); 
int Build = Convert.ToInt32(Components[3]); 
Build++; 
string newApplicationVersion 
    = string.Format("{0}.{1}.{2}.{3}", Maj, Min, Revision, Build); 
+0

這實際上阻止了我THX :) –

1

你可以嘗試SplitJoin

string currentApplicationVersion = "1.2.3.4"; 

int[] data = currentApplicationVersion.Split('.') 
    .Select(x => int.Parse(x, CultureInfo.InvariantCulture)) 
    .ToArray(); 

// The last version component is data[data.Length - 1] 
// so you can, say, increment it, e.g. 
data[data.Length - 1] += 1; 

// "1.2.3.5" 
String result = String.Join(".", data); 
+0

爵士漂亮的喜歡,但它沒有奏效(這可能是我的錯誤)。 :) –

+0

@KenZöggeler:對於錯字我感到抱歉:它應該是'x =>'而不是'x =>'(額外的空間) –

+0

我也修正了這個錯誤,但它仍然無效。 –

6

就做簡單的方法,

string v1 = "1.0.0.1"; 
    string v2 = "1.0.0.4"; 

    var version1 = new Version(v1); 
    var version2 = new Version(v2); 
    var result = version1.CompareTo(version2); 
    if (result > 0) 
     Console.WriteLine("version1 is greater"); 
    else if (result < 0) 
     Console.WriteLine("version2 is greater"); 
    else 
     Console.WriteLine("versions are equal"); 
+1

+1版本'類我沒有意識到。 – Codor

+0

:)謝謝@Codor! – iJay

+0

先生很好的答案,但它沒有奏效(這可能是我的錯誤)。 :) –

1

有一個與版本號一起工作的類構建。這就是所謂的Version,可以在System命名空間中找到

你可以通過代表的版本給構造函數的字符串解析當前版本

var currentApplicationVersion = new Version(currentApplicationVersionString); 

再拿到新的與另一個構造

var newApplicationVersion = new Version(
           currentApplicationVersion.Major, 
           currentApplicationVersion.Minor, 
           currentApplicationVersion.Build, 
           currentApplicationVersion.Revision +1  
          ); 

,然後只需撥打.ToString()如果你需要它作爲一個字符串

+0

謝謝,我已經擁有它,但它也工作。 :) –

+0

是的我知道你已經有問題的解決方案,但想用基礎類庫的功能構建一個解決方案。一般建議使用BCL,而不是實現你自己的相同功能的版本(在這種情況下,解析版本號並反映相同的字符串表示) –

+0

Thx無論如何:) 只是一個小問題:「Bcl? 「 :o –