using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:/temp/MyTest.txt" ;
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello" );
sw.WriteLine("And" );
sw.WriteLine("Welcome" );
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("This" );
sw.WriteLine("is Extra" );
sw.WriteLine("Text" );
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "" ;
while ((s = sr.ReadLine()) != null )
{
Console.WriteLine(s);
}
}
}
}
C#streamwriter写文件
最新推荐文章于 2026-05-06 07:29:10 发布
本文介绍了一个使用C#进行文件读写的简单示例。首先检查文件是否存在,如果不存在则创建并写入欢迎信息;之后无论文件是否存在都将追加额外的文本,并最终读取整个文件的内容。
9520

被折叠的 条评论
为什么被折叠?



