我已经实现了一些代码,以便对我的csv文件进行更改。但是,每次运行程序时,都会出现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 :(得分:0)
我不知道你要做什么,但问题在于:
lineElements[4] = lineElements[4].Replace(' ', ',');
数组lineElements
您的filePath
变量包含Path.Combine(Directory.GetCurrentDirectory(), "kaviaReport 02_08_2016.csv");
。所以它应该是这样的: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
)除以,
。如您所见,您的路径中没有任何,
。因此,您只能使用索引 0 的一个元素获得数组lineElements
。但是你试图按索引 4 获取元素。
lineElements[4] = lineElements[4].Replace(' ', ',');
正如预期的那样,你得到了 IndexOutOfRangeException