2016-08-12 90 views
-2

我已經實現了一些代碼,以便對我的csv文件進行更改。但是,每次運行該程序時,我都會遇到一個IndexOutOfRangeException錯誤。IndexOutOfRangeException未處理警告

class Program 
{ 
    static void Main(string[] args) 
    { 
     var filePath = Path.Combine(Directory.GetCurrentDirectory(), "kaviaReport 02_08_2016.csv"); 
     var fileContents = ReadFile(filePath); 

     foreach (var line in fileContents) 
     { 
      Console.WriteLine(line); 
     } 

     Console.WriteLine("Press any key to exit..."); 
     Console.ReadKey(); 
    } 

    public static IList<string> ReadFile(string fileName) 
    { 
     var results = new List<string>(); 
     int lineCounter = 0; 
     string currentLine = string.Empty; 
     var target = File.ReadAllLines(fileName); 
     //.Skip(1) // Skip the line with column names 
     while ((currentLine = fileName) != null)//while there are lines to read 
     { 
      if (lineCounter != 0) 
      { 
       //If it's not the first line 
       var lineElements = currentLine.Split(',');//split your fields into an array 
       lineElements[4] = lineElements[4].Replace(' ', ',');//replace the space in position 4(field 5) of your array 
       //target.WriteAllLines(string.Join(",", fielded));//write the line in the new file 
       File.WriteAllLines(fileName, target); 
      } 

      lineCounter++; 

     } 

     return results; 
    } 
} 
} 
+0

請修改你的問題一點,不要讓我們做所有的工作。 請參閱[mcve](http://stackoverflow.com/help/mcve) –

+0

答案有助於解決錯誤嗎? – Marusyk

回答

0

我不知道你正在嘗試做的,但問題是在這裏:

lineElements[4] = lineElements[4].Replace(' ', ','); 

您不必在陣列lineElements

filePath變量containts Path.Combine(Directory.GetCurrentDirectory(), "kaviaReport 02_08_2016.csv"); 5個元素。因此,它應該是這樣的:C:\Project\Bin\kaviaReport 02_08_2016.csv

然後你將它傳遞到ReadFile()fileName

後,在線路

while ((currentLine = fileName) != null) 

你設置爲currentLine值相同fileName和檢查NULL。所以現在你有兩個變量具有相同的值。然後你分割價值(如:C:\Project\Bin\kaviaReport 02_08_2016.csv,。正如你所看到的,你的道路上沒有任何,。因此,只有一個索引爲的元素可以獲得數組lineElements。但你試圖通過索引獲得元素。如預期

lineElements[4] = lineElements[4].Replace(' ', ','); 

所以你得到IndexOutOfRangeException