当前位置:K88软件开发文章中心编程语言.NET.NET01 → 文章内容

C#读写文本文件的方法

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2018-12-31 11:47:19

:2010-08-01 15:53:00

很多情况下,我们可能在程序中操作文件来读取或存放一些内容,下面给出具体的例子。

using System;
using System.IO;
namespace ConsoleApplication2
{
/// <summary>
/// Summary description for Class2.
/// </summary>
public class Class1
{
private const string FILE_NAME="MyFile.txt";
public static void Main(String[] args)
{
StreamWriter sr;
string report;
if(File.Exists(FILE_NAME)) //如果文件存在,则创建File.AppendText对象
{
sr=File.AppendText(FILE_NAME);
report="appended";
}
else //如果文件不存在,则创建File.CreateText对象
{
sr=File.CreateText(FILE_NAME);
report="created";
}

sr.WriteLine("This is my first file.");
Console.WriteLine("{0} {1}",FILE_NAME,report);
sr.Close();
}
}
}



C#读写文本文件的方法