Results 1 to 2 of 2

Thread: FileContentToArray

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Posts
    1,539

    FileContentToArray

    Code:
    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;
    }

  2. #2
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985
    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:
    Code:
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width