How to read a text file into a string variable

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?
 
J

John Timney \( MVP \)

StreamReader SR;
string S;
SR=File.OpenText(filename);
S=SR.ReadLine();
while(S!=null) {
Console.WriteLine(S);
S=SR.ReadLine();
}
SR.Close();
 
D

Daniel Fisher\(lennybacon\)

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?
 
H

Hans Kesting

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

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top