2014-11-04 104 views
0

雖然還有其他帖子,但我沒有得到適合我的問題的解決方案。未處理的異常:輸入的字符串格式不正確

調試器指向本聲明

id = Convert.ToInt32(s); 

它工作在開始罰款,但現在它產生錯誤。以下是完整的功能。作爲一個方面說明,我下面的N層架構在Visual Studio 2013年

public List<ATMBO> GetDataFromFile() // get data from file and store it into object and pass to BLL !!!! 
{ 
     List<ATMBO> l = new List<ATMBO>(); 

     // opening stream !!! 
     FileStream f = new FileStream("BankClient.txt", FileMode.Open); 
     StreamReader sr = new StreamReader(f); 

     if (!File.Exists("BankClient.txt")) 
     { 
      Console.WriteLine("{0} does not exist.", "BankClient.txt"); 
     } 

     // Start reading from file 
     string record=sr.ReadLine(); 
     //sr.ReadLine(); 

     while((record = sr.ReadLine()) != null) 
     { 
      //record = sr.ReadLine(); 
      // storing data from file to object!!!! 

      string [] data = record.Split(':'); 
      //Console.WriteLine(data[0]); 
      ATMBO bo = new ATMBO(); 
      string s = (data[0]); 
      int id = 0; 

      try 
      { 
       id = Convert.ToInt32(s); 
      } 
      catch (FormatException e) 
      { 
       Console.WriteLine("Input string is not a sequence of digits."); 
      } 
      catch (OverflowException e) 
      { 
       Console.WriteLine("The number cannot fit in an Int32."); 
      } 

      bo.ID1 = id; 
      bo.Login = data[1]; 
      bo.Type = data[2]; 
      string ss = (data[3]); 
      int blnc = Convert.ToInt32(ss); 
      bo.Balance = blnc; 
      bo.Status = data[4]; 
      bo.Date = data[5]; 
      bo.Pin = data[6]; 
      l.Add(bo); 
     } 

     sr.Close(); 
     f.Close(); 
     return l; 
    } 

BankClient.txt文件的內容:

ID:Name:Type:Balance:Status:Date:Pin 
00:Admin:Savings:500:Active:1/11/2014:111 
01:Nabeel:Savings:0:Active:1/11/2014:222 
02:Asad:Current:600:Active:2/11/2014:333 
03:Aqsa:Current:-300:Active:3/11/2014:ABC 
04:Umer:Savings:1000:Active:4/11/2014:444    
05:Ali:Savings:1000:Active:4/11/2014:555 
+4

's'的價值是什麼,什麼是您的'CurrentCulture'?調試您的代碼並告訴我們。如果在你的第一行失敗了,'data [0]'指向'ID'字符串(因爲你用':'分隔),並且顯然它不是一個有效的字符串。您是否嘗試跳過此文本文件的第一行?看起來你不需要它。 – 2014-11-04 07:59:19

+0

@SonerGönül我已編輯的帖子請審查! – EM923 2014-11-04 08:00:47

+2

在'string s =(data [0])上放置一個斷點;'看看這個值是什麼。從你發佈的內容看,它看起來應該可以工作,但最快的方法是使用調試器。 – Tim 2014-11-04 08:01:46

回答

1

您需要添加一些錯誤處理代碼,以確保沒有你可以工作的實際價值,如

string [] data = record.Split(':'); 
if(data.length < 7) 
    Console.WriteLine("Data doesn't contain what was expected"); 

更重要的是,而不是Convert.ToInt32可以使用TryParse

int id; 
if(!int.TryParse(s, out id)) 
    Console.WriteLine("Not a valid id"); 
+0

這是行得通的,但通過遍歷數據,它顯示記錄正確但兩次顯示「數據不包含所期望的」! – EM923 2014-11-04 08:42:36

+0

@ EM923在這個'WriteLine'上設置一個斷點,看看'data'和'record'包含了什麼,然後你的文本文件包含無效的行。 – Sayse 2014-11-04 08:43:48

+0

我不明白爲什麼數據數組有較少的長度,然後七有時!我調試但沒有正確地得到它! – EM923 2014-11-04 11:45:34