当前位置:首页>网络学院>程序开发>ASP.NET教程>文章内容

在c#中如何操作文本文件

[ 来源:www.it55.com | 作者: | 时间:2007-07-15 | 收藏 | 推荐 ] 【

// C#文本文件操作
//如何向现有文件中添加文本

www.it55.com

using System;using System.IO;
class Test {
public static void Main() {
// Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. using
(StreamWriter sw = new StreamWriter("TestFile.txt"))
{// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
}
}
}

www.it55.com在线教程

//如何创建一个新文本文件并向其中写入一个字符串。WriteAllText方法可提供类似的功能。
using System;
using System.IO;
public class TextToFile {
private const string FILE_NAME = "MyFile.txt";
public 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} or floats {1}, and so on.", 1, 4.2);
sw.Close();
}
}
}

vd;k;l www.it55.com rdfg


//如何从文本文件中读取文本
using System;using System.IO;
class Test {
public static void Main()
{
try{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message); www.it55.com在线教程
}
}
}

http://www.it55.com/

//在检测到文件结尾时向您发出通知。通过使用 ReadAll 或 ReadAllText 方法也可以实现此功能。
using System;using System.IO;
public class TextFromFile {
private const string FILE_NAME= "MyFile.txt";
public static void Main(String[] args)
{
if (!File.Exists(FILE_NAME))
{
Console.WriteLine("{0} does not exist.", FILE_NAME);
return;
}
using (StreamReader sr = File.OpenText(FILE_NAME))
{
String input;
while ((input=sr.ReadLine())!=null){
Console.WriteLine(input);
}
Console.WriteLine ("The end of the stream has been reached."); www.it55.com在线教程
sr.Close();
}
}

www.it55.com

来源:csdn IT资讯之家 www.it55.com

(编辑:IT资讯之家 www.it55.com

返回顶部
 

网友评论

[以下评论为网友观点,不代表本站。请自觉遵守互联网相关政策法规,所有连带责任均有评论者自负。]
[不超过250字]

图片文章