日期:2014-05-18 浏览次数:21178 次
FileInfo fi = new FileInfo(FILE_NAME);
if (!fi.Exists)
{
using (StreamWriter sw = fi.CreateText())
{
sw.WriteLine("hello word");
sw.Close();
}
}
using (StreamWriter sw = new StreamWriter(FILE_NAME, true, Encoding.UTF8))
{
sw.WriteLine("hello word");
sw.Close();
}
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c: test.txt";
FileInfo fi = new FileInfo(path);
// Delete the file if it exists.
if (fi.Exists)
{
fi.Delete();
}
//Create the file.
using (FileStream fs = fi.Create())
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is some text in the file.");
//Add some information to the file.
fs.Write(info, 0, info.Length);
}
//Open the stream and read it back.
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
FileInfo.OpenText 方法:创建使用 UTF8 编码、从现有文本文件中进行读取的 StreamReader。
返回值:使用 UTF8 编码的新 StreamReader。
FileInfo.CreateText 方法:创建写入新文本文件的 StreamWriter。
返回值:新的StreamWriter。
下面说明 CreateText 方法和OpenText 方法。
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c: test.txt";
FileInfo fi = new FileInfo(path);
if (!fi.Exists)
{
//Create a file to write to.
using (StreamWriter sw = fi.CreateText())
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
//Open the file to read from.
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}