如何使用C#读取文本文件

qazxsw1982103 2005-04-24 08:00:49
比如我有一文件名为OPT.TXT

该文件的路径为C:/TEMP/CONFIG/OPT.TXT

请问如何将该文件中的内容完整读出,并放到一个String 变量里???

...全文
148 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
dreamy835 2005-05-08
  • 打赏
  • 举报
回复
wsh236 2005-05-08
  • 打赏
  • 举报
回复
using System.IO;
using System.Text;


public class ReadText : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lblFile;

private void Page_Load(object sender, System.EventArgs e)
{

FileStream fs = new FileStream("C:/TEMP/CONFIG/OPT.TXT",FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(fs,Encoding.Default);
StringBuilder output = new StringBuilder();
string rl;
while((rl=sr.ReadLine())!=null)
{
output.Append(rl+"<br>");
}
lblFile.Text = output.ToString();
}

}
viyo 2005-04-24
  • 打赏
  • 举报
回复
using System;
using System.IO;
class MainClass
{
public static void Main()
{
StreamReader reader=new StreamReader(@"C:/TEMP/CONFIG/OPT.TXT");
string line;
string content="";

try
{


while((line=reader.ReadLine())!=null)
{
content+=line;
}

}
catch(Exception e)
{
Console.WriteLine(e.Message);
}

Console.WriteLine(content); //文本内容在content中
}
}
eplox 2005-04-24
  • 打赏
  • 举报
回复
2楼有意思。俺也经常在 windows 的命令行里敲 ls 和 clear
_-_-_-_- 2005-04-24
  • 打赏
  • 举报
回复
谢谢了~~学习
以前的大菠萝 2005-04-24
  • 打赏
  • 举报
回复
机器人 2005-04-24
  • 打赏
  • 举报
回复
FileStream fs = new FileStream("C:/TEMP/CONFIG/OPT.TXT", FileMode.Open, FileAccess.Read);

我说怎么看得怪怪的,路径符号写反了嘛。
改为:
FileStream fs = new FileStream(@"C:\TEMP\CONFIG\OPT.TXT", FileMode.Open, FileAccess.Read);
机器人 2005-04-24
  • 打赏
  • 举报
回复
using System.IO;

FileStream fs = new FileStream("C:/TEMP/CONFIG/OPT.TXT", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
try
{
string strData = sr.ReadToEnd();
}
catch(Exception ex)
{}
finally
{
sr.Close();
fs.Close();
}

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧