C# 尝试覆盖.txt文件c时出现奇数System.IndexOutOfRangeException#

C# 尝试覆盖.txt文件c时出现奇数System.IndexOutOfRangeException#,c#,arrays,indexoutofrangeexception,C#,Arrays,Indexoutofrangeexception,我想在.txt文件中扩展数据收集 我正在将.txt文件读入字符串数组。然后我制作了一个包含5个元素的新字符串数组 string oldarray[] = File.ReadAllLines(targetfile); //it is correctly reading the file string newarray[] = new string[oldarray.Count()+5]; for (int i = 0; i < oldarray.Count(); i++) {

我想在.txt文件中扩展数据收集

我正在将.txt文件读入字符串数组。然后我制作了一个包含5个元素的新字符串数组

string oldarray[] = File.ReadAllLines(targetfile);   //it is correctly reading the file
string newarray[] = new string[oldarray.Count()+5];

for (int i = 0; i < oldarray.Count(); i++) {         //copy old array into new bigger one
    newarray[i] = oldarray[i];
}
newarray[oldarray.Count() + 1] = "Data1";  //fill new space with data
newarray[oldarray.Count() + 2] = "Data2";
newarray[oldarray.Count() + 3] = "Data3";
newarray[oldarray.Count() + 4] = "Data4";
newarray[oldarray.Count() + 5] = " ";     //spacer

//now write new array into same textfile over old data
File.WriteAllLines(targetfile, newarray);  //System.IndexOutOfRangeException
string oldarray[]=File.ReadAllLines(targetfile)//它正在正确读取文件
string newarray[]=新字符串[oldarray.Count()+5];
对于(int i=0;i
我也试着像这样逐行写入文件,但它确实抛出了相同的异常:

using (StreamWriter writer = new StreamWriter(destinationFile)) //System.IndexOutOfRangeException 
{
    for (int i = 0; i < newarray.Length; i++)
    {
        writer.WriteLine(newarray[i]);
    }
}
使用(StreamWriter writer=newstreamwriter(destinationFile))//System.IndexOutOfRangeException
{
for(int i=0;i

它为什么会这样做,我如何修复它?

数组索引是基于零的,因此
oldarray.Count()+5
指向数组末尾之后的元素。第一个元素也保留为空

这可以通过将索引固定在0和4之间而不是1和5之间来解决。不过,更好的解决方案是将行作为列表加载并附加新字符串:

string lines = File.ReadLines(targetfile).ToList();
var newLines=new[] {"Data1","Data2"...};
lines(newLines);
File.WriteAllLines(targetfile, lines);
甚至

var newLines=....;
string lines = File.ReadLines(targetfile)
                   .Concat(newLines)
                   .ToList();
File.WriteAllLines(targetfile, lines);

ReadAllLines
并以数组形式返回列表的副本<另一方面,code>ReadLines
每次返回一行作为
IEnumerable
。只要迭代
IEnumerable
文件,文件就会保持打开状态,因此我们需要
ToList()
来使用它,并允许文件在覆盖它之前关闭。

您的关闭间隔为一-olaArray
中的最后一个元素位于
oldarray.Count()-1,而不是
oldarray.Count()

for(int i=0;i
新数组中不存在索引
oldarray.Count()+5

数组索引从零开始。如果有一个包含10个元素的数组,那么第一个索引是0,最后一个索引是9。如果使用
oldarray.Count()+5
项创建一个新数组,它将有15项,最后一个索引将为14项(不是
oldarray.Count+5
,它等于15)

就这样做吧:

newarray[oldarray.Count()] = "Data1";
newarray[oldarray.Count() + 1] = "Data2";
newarray[oldarray.Count() + 2] = "Data3";
newarray[oldarray.Count() + 3] = "Data4";
newarray[oldarray.Count() + 4] = " ";
我打赌这条线上不会发生异常
newarray[oldarray.Count()] = "Data1";
newarray[oldarray.Count() + 1] = "Data2";
newarray[oldarray.Count() + 2] = "Data3";
newarray[oldarray.Count() + 3] = "Data4";
newarray[oldarray.Count() + 4] = " ";