2016-08-23 63 views
1

發現我有一個ST-LINK程序固件太,然後將報表上的緩衝區大小提出的申請,數據位等無法找到一個文本文件c#

我有一個文本文件中的數它存儲了這些結果。但是,一批中可能有很多電路板,每次需要增加一個產品編號。所以我想要做的是讓程序看看最後的董事會報告,看看它是否有相同的批號(因爲批次將一次完成),如果它確實增加了1的產品編號。如果它沒有相同的批號,那麼它必須是新批次,產品編號將爲1.

目前產品編號未更新。每次它返回1. 這裏是我的代碼:

  public int previousNumber() 
    { 
     int pNumber = 0; 
     string line; //set string 
     int counter = 0; //create int 
     int numberOfLines = File.ReadLines("report.txt").Count(); 

     System.IO.StreamReader file = new System.IO.StreamReader("report.txt"); //create streamreader 

     while ((line = file.ReadLine()) != null) //until no empty lines 
     { 
      string[] allLines = File.ReadAllLines("report.txt"); //read in report file 

      if (allLines[numberOfLines - 9] == batchNumberTextBox.Text) 
      { 
       pNumber = int.Parse(allLines[numberOfLines - 7]); 
      } 
      else 
      { 
       pNumber = 0; 

      } 
     } 
     file.Close(); 
     pNumber = pNumber + 1; 
     return pNumber; 
    } 

    private void saveReport() 
    { 
     getValues(); 

      int number = previousNumber(); 
      BatchNumber = batchNumberTextBox.Text; 
      SerialNumber = serialNumberTextBox.Text; 
      ProductNumber = number; 
      string ProductNumberString = ProductNumber.ToString(); 
      string inDate = DateTime.Now.ToString("f", 
        CultureInfo.CreateSpecificCulture("en-UK")); //set date in that format 

      try 
      { 
       board newBoard = new board(BatchNumber, SerialNumber, ProductNumberString, BufferSize, StopBits, Parity, DataBits, baudRate, inDate); 
       newBoard.Save("report.txt"); 
       File.AppendAllText("batches.txt", "BATCH NUMBER: " + BatchNumber + " - DATE: " + inDate + Environment.NewLine); 
       System.Windows.MessageBox.Show("Report Saved"); 
      } 
      catch 
      { 
       System.Windows.MessageBox.Show("Save failed"); //tell user save failed 
      } 

     } 

這裏是爲報告的文本文件:

enter image description here

你能看到的任何地方,爲什麼它可能無法正常工作?我覺得我可能對此有一個奇怪的方式,所以如果你能想出一個更好的方式,將會非常感激!

謝謝你在前進, 露西

回答

1

我把它,批號爲1234的數據樣本。如果是這樣,它從最後一行的偏移是-10而不是。這是你的錯誤的主要來源。

你的代碼中還有很多冗餘:在讀取一次的同時多次讀取整個文件,並將其所有行存儲在一個數組中將會相當不錯。

簡化(但仍然是正確的)的previousNumber()版本可能是這樣的:

public int previousNumber() 
{ 
    var allLines = File.ReadAllLines("report.txt"); 
    int pNumber = 0; 
    if (allLines.Length > 10 && allLines[allLines.Length - 10] == batchNumberTextBox.Text) 
     // Note: if the desired value is "1" and not "4096", then the offset is "-8". 
     int.TryParse(allLines[allLines.Length - 8], out pNumber); 
    return pNumber + 1; 
} 
+0

完美非常感謝你! – lucycopp