File.ReadAllLines(FileName)数组大小限制 [英] File.ReadAllLines(FileName) array size limit
问题描述
如果我使用:
字符串 FileName = " ;
字符串 [] DataFile = File.ReadAllLines(FileName);
现在说文件有5行...
因此,DataFile数组的最后一个文件行位于4.
如果我想在DataFile [5]处添加一行(它位于数组的底部,并且超过文件位置的末尾),则会得到一个OutOfRangeException,这是可以理解的.做我想做的最好的方法是什么?
正如GanesanSenthilvel所说,使用List< string>而是使用Array.Resize()方法.
以下是一些示例:
列表< string> dataFile = 新列表< string>(); dataFile.AddRange(File.ReadAllLines(FileName));
那么您可以用相同的方式添加其他文件行
dataFile.AddRange(File.ReadAllLines(SomeOtherFile));
或
字符串 [] data = 新 " 等等", 等等等等", 等等等等"}; dataFile.AddRange(data);
或一行
dataFile.Add(" ); pre>
或
字符串 someData = " ; dataFile.Add(someData);
如果您确实想使用Array.Resize()方法,也可以使用
字符串 [] data = 新 2 ]; data [ 0 ] = " ; data [ 1 ] = " 跨度>; Array.Resize( ref data,data.Length + 1 ); data [ 2 ] = " span>;
您的目标是将行添加到现有文件的末尾
为什么不使用此代码
StreamWriter sw= File.AppendText("c:\\temp.txt"); sw.WriteLine(); sw.WriteLine("hello"); sw.Flush(); sw.Close();
谢谢
--RA
您可以很好地使用List< string> </ 字符串 >以避免OutOfRangeException
If I use:
string FileName = "MyFile.txt";
string[] DataFile = File.ReadAllLines(FileName);
Now say the file has 5 lines...
Therefore the DataFile array will have its last file line on 4.
If I want to add a line at say DataFile[5] (which is at the bottom of the array and past the end of file position), I get an OutOfRangeException which is understandable. What is the best way to do what I want to do? essentially I want the array to be resized.
As GanesanSenthilvel said use a List<string> instead or the Array.Resize() method.
Here are some examples:
List<string> dataFile = new List<string>(); dataFile.AddRange(File.ReadAllLines(FileName));
then you could add another files lines in the same way
dataFile.AddRange(File.ReadAllLines(SomeOtherFile));
or
string[] data = new string[] { "blah", "blah blah", "blah blah blah" }; dataFile.AddRange(data);
or a single line
dataFile.Add("some line of data");
or
string someData = "blah blah blah blah"; dataFile.Add(someData);
You could if you really wanted to use the Array.Resize() method i.e.
string[] data = new string[2]; data[0] = "some data"; data[1] = "some more data"; Array.Resize(ref data, data.Length + 1); data[2] = "even more data";
Your Target is add line to the existing file at end
why don''t you use this code
StreamWriter sw= File.AppendText("c:\\temp.txt"); sw.WriteLine(); sw.WriteLine("hello"); sw.Flush(); sw.Close();
Thanks
--RA
Instead of array of String, you can very well useList<string></string>to avoid OutOfRangeException
这篇关于File.ReadAllLines(FileName)数组大小限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!