Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi

 

I am creating a method that reads a file's 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 object's data has yet to be received. So I'm 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;

  • *Experts*
Posted
Try this:
StreamReader srReader = new StreamReader(FilePath); // Open the file
String sFileContents = srReader.ReadToEnd(); // Read the entire contents

// Remove all carriage returns, since the Split function can't have delimiters that are more than one
// character, so we'll 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.

  • *Experts*
Posted
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.
Posted

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;

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...