2014-02-25 86 views
2

中的一些文本使用streamReader讀取文件。
如果行以1開頭,我想使用這一行。
該生產線將讀取類似:1,103,1,4454:HH通讀流讀取器並使用行

所以我想第一,之後,但在第二次前搶號。所以我需要103並將其分配給產品編號:

int ProductID; 

using (StreamReader sr = new StreamReader(fakeFileToProcess)) 
{ 
    while (!sr.EndOfStream) 
    { 
     string line = sr.ReadLine(); 

     if (line.StartsWith("1,")) 
     { 
      //so line will be 1,103,1,44543:HH 
      //How do I capture the '103'...something like: 
      //ProductID = line.read between "1," & ","(next comma) 

     } 

     if (line.StartsWith("25")) 
     { 
      continue; 
     } 
    } 
} 

回答

1

可以使用String.Split()函數來實現這一目標:

從MSDN:String.Split()

返回一個字符串數組該字符串包含此字符串 中的子字符串,它們由指定字符串數組的元素分隔。 A 參數指定是否返回空數組元素。

試試這個:

string num = line.Split(',')[1].Trim(); 
if(int.TryParse(str,out ProductID) 
{ 
    //success now ProductID contains int value (103) 
} 

完整代碼:

int ProductID;  
using (StreamReader sr = new StreamReader(fakeFileToProcess)) 
{ 
    while (!sr.EndOfStream) 
    { 
     string line = sr.ReadLine(); 

     if (line.StartsWith("1,")) 
     { 
      string num = line.Split(',')[1].Trim(); 
      if(int.TryParse(str,out ProductID) 
      { 
       //parsing is successful, now ProductID contains int value (103) 
      }  
     } 

     if (line.StartsWith("25")) 
     { 
      continue; 
     } 
    } 
} 
1

使用string.IndexOf當你有一個如此清晰分隔的數據。
IndexOf比分裂在其部分字符串更好,因爲你並不需要創建的字符串

if (line.StartsWith("1,")) 
    { 
     // search the second comma after the first one.... 
     int pos = line.IndexOf(',', 2); 

     // for simplicity, do not check if you really have found a second comma.... 
     string id = line.Substring(2, pos - 2); 

     // Try to convert whatever is between the first comma and the second one.. 
     if(Int32.TryParse(id, out productID)) 
      Console.WriteLine("Got it:" + productID.ToString()); 

    } 
0

的陣列可以使用string.Split()方法acheive你想要什麼。 要轉換爲int,請使用int.Parse()方法。

所以,你可以做到以下幾點:

List<string> items = line.Split(','); 
ProductID = int.Parse(items[1]);