PDA

Click to See Complete Forum and Search --> : FileContentToArray


kovan
Jan 3rd, 2004, 05:27 PM
private ArrayList fileContentToArrayList(string filePath)
{

System.Collections.ArrayList arrListLines = new System.Collections.ArrayList();
//read the file content one by one
try
{
StreamReader fl = new StreamReader(filePath, System.Text.Encoding.ASCII);
//StreamReader fl = File.OpenText(filePath,);
string line = "";
while((line = fl.ReadLine()) != null )
{
arrListLines.Add(line);
}


}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message, "Failed reading file");
return null;
}
return arrListLines;
}

Kasracer
Jan 13th, 2004, 03:04 PM
In your code, you pass an array (which could be huge, or small, you don't know) by value. You then declare a new ArrayList as well as a streamreader and a string. You Then return the entire Array (which could be friggin huge).

That isn't very efficient.

Take a look at this:

private void fileContentToArrayList(string filePath, ref System.Collections.ArrayList arryList)
{
try
{
using(System.IO.StreamReader fin = new System.IO.StreamReader(filePath, System.Text.Encoding.ASCII))
{
while ((filePath = fin.ReadLine()) != null)
{
arryList.Add(filePath);
}
}
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message, "Failed reading file");
}
}

Once the filePath string is used the first time, it will never be used again in that function, so just reuse it instead of re-declaring another string. I also pass an arraylist by reference. There is no sence in passing it by value, and then creating yet another arraylist (which is the same as having 2 arraylists in 1 function). Also, instead of returning a very large ArrayList, which could be time consuming, I modify it by reference so you won't experience a slow down when the function leaves. Then I put the streamreader declaration in a using statement. According to the MSDN, once the using statement is finished running, the streamreader will be immediately released from memory.