Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

file read 1

Status
Not open for further replies.

Cagliostro

Programmer
Sep 13, 2000
4,226
GB
say me please how to read entirely a small ASCII text file in a string variable?

Ion Filipski
1c.bmp
 
Even there is a small file , a StringBuilder will be used to read in the whole file.

Code:
using System;
using System.IO;
using System.Text;
StringBuilder ReadFile(string sPathFile)
{
	StreamReader sr = null;
	System.Text.StringBuilder sb = null;
	try
	{
		sb = new System.Text.StringBuilder();
		sr = new StreamReader(sPathFile);
		string line ="";
		while ((line = sr.ReadLine()) != null)  
		{
		    sb.Append (line);
		}
	}
	catch (Exception e)
	{
	string sMsg = "Error reading file : " + sPathFile + " into a StringBuilder " + e.GetType() + e.Message;
	throw new Exception (sMsg);
	}
        finnaly
        {
         if (sr !=null)
	    sr.Close();
         sr = null;
        } 
 	return sb;
}
How to use:
StringBuilder sb = ReadFile("C:\\todo.txt");
if (sb !=null)
{
 string sTemp = sb.ToString();
}
-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top