1.向文本中写入文本
下面的示例可向文本现有的文件中添加文本
string path =
@"..\..\TestFile.Text";
using (StreamWriter sw = new
StreamWriter(path))
{
sw.Write("This is the
");
sw.WriteLine("header for the
file.");
sw.WriteLine("-------------------------");
sw.Write("The date
is:");
sw.WriteLine(DateTime.Now);
}
运行后程序在指定路径的文件夹中建立一个文本文件TestFIle.txt,文本内容为:
This is the header for the file.
-------------------------
The date
is:2014/3/12 17:37:52
下面的示例创建一个新文本文件并向其中写入一个字符串。WriteAllTest方法可提供类似的功能:
private const string FILE_NAME =
@"..\..\MyFile.txt";
static void
Main(string[] args)
{
if
(File.Exists(FILE_NAME))
{
Console.WriteLine("{0}already
exists.",FILE_NAME);
return;
}
using
(StreamWriter sw =
File.CreateText(FILE_NAME))
{
sw.WriteLine("This is my
file");
sw.WriteLine("I can write ints{0} of floats{1},and so
on.",1,4.2);
}
}
运行后程序在项目文件夹建立一个文本文件MyFile.txt,文件内容为:
This is my file
I can write ints1 of floats4.2,and so on.
2.从文本读取文本
下面的代码示例演示如何从文本文件中读取文本。第二个实例在检测到文件结尾时发出通知。
try
{
string path =
@"..\..\TestFile.txt";
using(StreamReader sr=new
StreamReader(path))
{
string
line;
//读和显示文本的行,直到文件结束
//while((line=sr.ReadLine())!=null)
line =
sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch(Exception
e)
{
Console.WriteLine("The file could not be
read:");
Console.WriteLine(e.Message);
}
下面的示例在检测到文件结尾时发出通知。
private const string FILE_NALE =
@"..\..\MyFile.txt";
static void
Main(string[] args)
{
if
(!File.Exists(FILE_NALE))
{
Console.WriteLine("{0}does not
exist.",FILE_NALE);
return;
}
using
(StreamReader sr =
File.OpenText(FILE_NALE))
{
string
input;
while ((input = sr.ReadLine()) !=
null)
Console.WriteLine(input);
Console.WriteLine("The end fo the stream has been
reached");
Console.ReadKey();
}
上面的代码通过调用File.OpenText创建一个指向MyFile.txt的StreamReader。StreamReader.ReadLine将每一行都作为一个字符串返回。当不再要读取的字段时,会有一条消息显示该情况,然后流关闭
原文:http://www.cnblogs.com/yk1992/p/3596894.html