2013-12-12 35 views
0

我目前正在在Windows上的库存应用程序分配形式C# 我的主要形式显示3个选项分别是:如何在Windows库存数据读取文件信息表格

  1. 注册产品
  2. 购买产品和
  3. 退出

对于选项1和3我已经有我需要什么。但是,对于选项2,即用户应该能够购买已经注册的产品的地方,我不知道如何在保存文件的位置“查找产品”。

文件存储这样的产品信息:(显示产品,数量,有多少件已售出的价格,从顶部到底部的名称)

Chair 

100 
10 
0 

Mouse 

95 
15 
5 

Laptop 

50 
13 
4 

我这样做之前,控制台应用程序,但我并没有存储在信息文件,我做到了与阵列和简单的使用“为”循环找到我需要的,并从那里我可以做其他的产品......

有人告诉我,在课堂上,我需要逐行阅读文件,直到找到需要的产品并将其变成变量为止?我如何在Forms平台上做到这一点?

+1

,问题是......? –

+0

@lazyberezovsky我想知道我必须做的逐行读取文件中的行,一旦我发现我所需要的产品,把它变成一个变量,所以我可以做其他,这将被减去一个特定产品的数量用户希望从可用该特定项目的单位数购买。 – mexman3217

回答

1

我在课上告诉我,我需要逐行读取文件中的行,直到我发现我所需要的产品,并把它变成一个变量?我如何在Forms平台上做到这一点?

假设文件格式是强一致,这样的事情应该工作:

//A class to hold the individual pieces of data 
    public class Item 
    { 
     public string Name = ""; 
     public int Qty = 0; 
     public double Price = 0; 
     public int QtySold = 0; 
    } 
    public Item FindItem(string filename, string itemname) 
    { 
     //An object of type Item that will hold the specific values 
     Item output = new Item(); 
     //The using block handles automatic disposal of the streamreader 
     using(StreamReader sr = new StreamReader(filename)) 
     { 
      //Read the file until the end is reached 
      while(!sr.EndOfStream) 
      { 
       //Check the string from the file against the item name you're 
       //looking for. 
       string temp = sr.ReadLine().Trim(); 
       if(temp == itemname) 
       { 
        //Once we find it, throw away the empty line and start 
        //assigning the data to the output object. 
        sr.ReadLine(); 
        output.Name = temp; 
        output.Qty = int.Parse(sr.ReadLine()); 
        output.Price = double.Parse(sr.ReadLine()); 
        output.QtySold = int.Parse(sr.ReadLine()); 
        //Since we found the item we're looking, there's no need 
        //to keep looping 
        break; 
       } 
      } 

     } 
     //The file is closed and output will either have real data or an empty 
     //name and the rest all 0's 
     return output; 
    } 
0

我想你是要求如何阅读文件的帮助,我是对吗?

以下链接可为您提供一个例子:

编辑:

using (StreamReader sr = new StreamReader("TestFile.txt")) 
{ 
    string line; 
    // Read and display lines from the file until the end of 
    // the file is reached. 
    while ((line = sr.ReadLine()) != null) 
    { 
     Console.WriteLine(line); 
    } 
} 

希望这可以帮助你。

+2

请不要发布裸露的链接。如果它包含问题的解决方案,请引用相关部分并解释它如何回答问题。如果链接消失,你的帖子对未来的访问者就没用了。 –

0

可以使用File.ReadAllLines方法将文件内容作为字符串数组获取。然后查找你想要的字符串,并在需要时获得相应的数据。

伪代码(假设你的文件结构如图所示)

string[] values = File.ReadAllLines(filepath); 
int count = values.Length; 

for (i = 0 to count - 1) 
    if(i%6 == 0) <compare your desired object to the objects from file> 
    if (match_found) <get the corresponding data for object from next 4 lines> 
相关问题