By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,491 Members | 1,108 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,491 IT Pros & Developers. It's quick & easy.

How to read a text file into a string variable

P: n/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?
Feb 23 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
StreamReader SR;
string S;
SR=File.OpenText(filename);
S=SR.ReadLine();
while(S!=null) {
Console.WriteLine(S);
S=SR.ReadLine();
}
SR.Close();

--
Regards

John Timney
Microsoft MVP

"ad" <fl****@wfes.tcc.edu.tw> wrote in message
news:uQ**************@TK2MSFTNGP11.phx.gbl...
I have a text file in the directory of my web application.
How can I read this text file into a string vaiable?

Feb 23 '06 #2

P: n/a
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:fl****@wfes.tcc.edu.tw]
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?
Feb 23 '06 #3

P: n/a
> 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
Feb 23 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.