How to read a text file into a string variable

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I have a text file in the directory of my web application.
How can I read this text file into a string vaiable?
 
StreamReader SR;
string S;
SR=File.OpenText(filename);
S=SR.ReadLine();
while(S!=null) {
Console.WriteLine(S);
S=SR.ReadLine();
}
SR.Close();
 
public string ReadFromFile(string filename)
{
StreamReader sr = File.OpenText(filename);

StringBuilder sb = new StringBuilder();
string str = sr.ReadLine();
while( str != null )
{
sb.Append(str + "\n");
str = sr.ReadLine();
}

sr.Close();
return sb.ToString();
}


Daniel Fisher(lennybacon) | Software Engineer | newtelligenceR AG
blog: http://staff.newtelligence.net/danielf
usergroup: http://vfl-niederrhein.net


-----Original Message-----
From: ad [mailto:[email protected]]
Posted At: Thursday, February 23, 2006 1:28 PM
Posted To: microsoft.public.dotnet.framework.aspnet
Conversation: How to read a text file into a string variable
Subject: How to read a text file into a string variable

I have a text file in the directory of my web application.
How can I read this text file into a string vaiable?
 
public string ReadFromFile(string filename)
{
StreamReader sr = File.OpenText(filename);

StringBuilder sb = new StringBuilder();
string str = sr.ReadLine();
while( str != null )
{
sb.Append(str + "\n");
str = sr.ReadLine();
}

sr.Close();
return sb.ToString();
}

or use ReadToEnd() :

string str;
using (StreamReader sr = File.OpenText(filename))
{ str = sr.ReadToEnd(); }


Hans Kesting
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top