File contents to array

SEVI

Well-known member
Joined
Jun 28, 2003
Messages
48
Location
Australia
Hi

I am creating a method that reads a files contents. I thought about returning the StreamReader object but went against it as I cannot close the object prior to exiting the method if the objects data has yet to be received. So Im trying to populate an array with the contents of the file, but am now running into problems with initialisation as I do not know how many lines of text are in the file. I seem to find no info that tells me C# array initialisation can be changed, is this true? Can I initilise the array to a line count of the file? Can a single string with multiple lines be converted into an array? Am I going about this the wrong way?

Thanks

string[] astrFileContents = new string[20];
int intCount = 0;
StreamReader srdStreamRead;
srdStreamRead=File.OpenText(FilePath);
astrFileContents[intCount] = srdStreamRead.ReadLine();
while(astrFileContents[intCount] != null) {
intCount++;
astrFileContents[intCount] = srdStreamRead.ReadLine();
}
srdStreamRead.Close();
return astrFileContents;
 
Try this:
C#:
StreamReader srReader = new StreamReader(FilePath); // Open the file
String sFileContents = srReader.ReadToEnd(); // Read the entire contents

// Remove all carriage returns, since the Split function cant have delimiters that are more than one
// character, so well remove Cr and use Lf.
sFileContents = sFileContents.Replace(ControlChars.Cr, "");

// Split the string into an array, using a Line-feed as the breaking point for each line
sLines = sFileContents.Split(ControlChars.Lf);
Now the sLines array contains all the lines in the file.
 
If you want an array you could also use an array list to first read all the inles and then use the .ToArray() method of the array list to get the contants to an array.
 
Thank-you both..

I got yours working first up VF. Had to change it a little to make C# happy. Will play around with the arraylist class also.

Thanks again..

string delimStr = "\n";
char [] delimiter = delimStr.ToCharArray();
StreamReader srdStreamRead = new StreamReader(FilePath);
String strFileContents = srdStreamRead.ReadToEnd();
string[] astrFileContents = strFileContents.Split(delimiter);
srdStreamRead.Close();
return astrFileContents;
 
Back
Top