Click here to Skip to main content
15,031,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If I use:

C#
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.
Posted

As GanesanSenthilvel said use a List<string> instead or the Array.Resize() method.

Here are some examples:

C#
List<string> dataFile = new List<string>();
dataFile.AddRange(File.ReadAllLines(FileName));


then you could add another files lines in the same way
C#
dataFile.AddRange(File.ReadAllLines(SomeOtherFile));


or
C#
string[] data = new string[] { "blah", "blah blah", "blah blah blah" };
dataFile.AddRange(data);


or a single line
C#
dataFile.Add("some line of data");

or
C#
string someData = "blah blah blah blah";
dataFile.Add(someData);


You could if you really wanted to use the Array.Resize() method i.e.
C#
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";
   
v4
Comments
Winston_D 2-Feb-12 9:46am
   
Thanx a million!
LanFanNinja 2-Feb-12 9:50am
   
You're welcome.

Note also that if you use a List<string> you could always convert it to an array for 'insert reason here' if you needed to. i.e.
List<string> data = new List<string>();
string[] dataArray = data.ToArray();
LanFanNinja 2-Feb-12 10:12am
   
Sorry there was an error in my code. =0
I modified my solution with the change below.

from
Array.Resize(ref data, data.Size + 1);
to
Array.Resize(ref data, data.Length + 1);

sorry if there was any problems because of this.

Good day.
Winston_D 2-Feb-12 11:18am
   
No problems. I caught on. thanx for the help
   
Of course. My 5.
--SA
LanFanNinja 3-Feb-12 1:53am
   
Thank you
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
   
Comments
Winston_D 2-Feb-12 11:17am
   
Thanks for the answer. I did not want to use the stream tools for doing this. wanted to try a different approach with some benefits that the stream tool doesnt have.
Instead of array of String, you can very well use
C#
List<string></string>
to avoid OutOfRangeException
   
Comments
Winston_D 2-Feb-12 11:16am
   
i am not very familiar with lists but thank. will do some research on it

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900