C# 中的 IO
C#与Java不同,不区分字符流、字节流,采用Stream方式,针对Stream提供Reader与Writer的相关操作。
摘几篇msdn的demo:
1.写操作 StreamWriter 类
StreamWriter 实现TextWriter接口,旨在以一种特定的编码输出字符,而从 Stream 派生的类则用于字节的输入和输出。
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);
}
}
}
2. 读操作 StringReader类
实现从字符串进行读取的 TextReader。
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);
}
}
}
关于C# IO操作详见msdn后续还会完善下最近工作中碰到的IO类