2017-03-17 16 views
-1

我需要得到的產品代碼,價格和庫存對包含如何閱讀和TXT一條線寫特定字在C#控制檯

//product code;product name;price;stock; 
c01;cappuccino;3500;12; 
c02;mocaccino;4000;15; 
c03;black coffe;3000;10; 
c04;chocolate milk;5000;19; 
c05;vanilla milk;5000;12; 
c06;strawberry milk;5000;13; 
c07;coke;3000;13; 
c08;fanta;3000;15; 
c09;sprite;3000;9; 
c10;orange juice;4500;10; 
c11;apple juice;4500;9; 
c12;mango juice;4500;18; 

我試過

txt文件計算
if(line.Contains("")) 

在line.contains給錯誤紅色下劃線,而我缺少使用命名空間爲此?

也是我試過

FileStream fs = new FileStream("product.txt", FileMode.OpenOrCreate, FileAccess.Read); 
    StreamReader sr = new StreamReader(fs); 

    sr.BaseStream.Seek(0, SeekOrigin.Begin); 
    string str = sr.ReadLine(); 
    while (str != null) 
    { 
     Console.WriteLine("{0}", str); 
     str = sr.ReadLine(); 
    } 
    sr.Close(); 
    fs.Close(); 

的做法得到一個字,但它從TXT代替

+1

_ 「但在line.contains行給出錯誤紅色下劃線代替,我失去了使用......」 _ - ** Pro Tip **:如果將鼠標移動到紅色下劃線/扭曲處並將鼠標懸停在那裏一會兒,Visual Studio將顯示一個工具提示,描述問題 – MickyD

回答

0

,如果你想要遍歷throught你可以把它像這樣的值返回的所有內容:

var streamReader = new StreamReader(new FileStream("c:\\file.txt")); 

while(!streamReader.EndOfStream) 
{ 
var line = streamReader.ReadLine() 
var values = line.Split(';'); 
for(var i = 0; i < line.Length; i++) 
    Console.WriteLine(values[i]); //example usage 
} 
1

使用下面的類和代碼,您將能夠提取所需的數據以進行計算和其他操作。

它基本上是逐行讀取文件並將它們解析到對象。
檢查"//"將跳過第一行。

希望這適合您的需求。

產品類別

public class Product 
{ 
    public string Code { get; set; } 
    public string Name { get; set; } 
    public decimal Price { get; set; } 
    public int Stock { get; set; } 
} 

文件解析

var products = new List<Product>(); 

using (var fileStream = new FileStream("product.txt", FileMode.OpenOrCreate, FileAccess.Read)) 
using (var streamReader = new StreamReader(fileStream)) 
{ 
    string line; 
    while (!String.IsNullOrWhiteSpace((line = streamReader.ReadLine()))) 
    { 
     if (!line.StartsWith("//")) 
     { 
      var lineSplit = line.Split(';'); 
      products.Add(new Product 
      { 
       Code = lineSplit[0], 
       Name = lineSplit[1], 
       Price = Decimal.Parse(lineSplit[2]), 
       Stock = Int32.Parse(lineSplit[3]) 
      }); 
     } 
    } 
} 
+0

,當我嘗試Console.WriteLine(linesplit [0])時;'它迴歸n所有產品代碼,我如何獲得唯一的產品代碼? – radren

+0

簡短而又甜美,足夠容易理解。儘管如此,我更喜歡它在F#中的外觀(請參閱http://ideone.com/ltCwka)。 :) – dumetrulo