在c#中如何操作文本文件
来源:互联网 发布:apm软件下载 编辑:程序博客网 时间:2024/05/16 19:21
// C#文本文件操作
//如何向现有文件中添加文本
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);
}
}
}
//如何创建一个新文本文件并向其中写入一个字符串。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();
}
}
}
//如何从文本文件中读取文本
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);
}
}
}
//在检测到文件结尾时向您发出通知。通过使用 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.");
sr.Close();
}
}
- 在c#中如何操作文本文件
- 在C#中如何:读写文本文件
- 如何在C#中轻松操作注册表
- 如何在C#中轻松操作注册表
- 如何在C#中轻松操作注册表
- 如何在C#中轻松操作注册表
- Attribute在C#中如何操作
- 如何将文本文件显示在RichEdit中
- c# 中读写ini文件(C#操作文本文件、C#读写文本文件)
- c#操作文本文件
- c#操作文本文件
- C#文本文件操作
- C#文本文件的操作
- C#操作文本文件
- C#操作文本文件
- c#操作文本文件
- C#操作文本文件
- C#文本文件操作
- Scott Mitchell 的ASP.NET 2.0数据教程之63:在事务里对数据库修改进行封装
- miranda-组件图
- MVC框架struts
- 编程隐藏磁盘
- miranda-用例图0
- 在c#中如何操作文本文件
- LUCENE 读书笔记 20070712
- 稀碎的时光
- Struts学习笔记(一)
- 网络IPC, socket(3): 建立连接
- Web.Config文件中关于Session
- 感悟设计
- 生产者-消费者问题
- 信监挂了