File FileStream StreamWriter StreamReader文件读写操作方法

string path = "D:\\AccountChecking\\Test.txt";
string content = "abcdefg\r\nhigklmn\r\nopqrst"; //操作文件夹对象,无则创建文件夹,可以一次创建多级
Directory.CreateDirectory("D:\\AccountChecking\\"); #region File-对于文件的典型操作,如复制、移动、重命名、创建、打开、删除和一次将追加到单个文件的类 //写文件
File.WriteAllText(path, content, Encoding.Default);
File.WriteAllLines(path, content.Split('r'), Encoding.Default);
File.WriteAllBytes(path, Encoding.Default.GetBytes(content));
//追加内容
File.AppendAllText(path, content, Encoding.Default);
//读文件
string content_t = File.ReadAllText(path, Encoding.Default);
string[] content_s = File.ReadAllLines(path, Encoding.Default);
byte[] content_b = File.ReadAllBytes(path); #endregion #region FileStream-以流的形式对文件系统上的文件进行读取、写入、打开和关闭操作,既支持同步读写操作,也支持异步读写操作 //写文件
using (FileStream fileStream = new FileStream(path, FileMode.Create))
{
byte[] data = Encoding.Default.GetBytes(content);
fileStream.Write(data, , data.Length);//将内容写入缓冲区
//Flush()将缓冲区内容写入文件系统,后续无操作的话,在关闭或出using时会自动写入文件系统
//fileStream.Flush();
//使用using就不必显示的关闭流,它会自动关闭并释放
//fileStream.Close();
}
//追加内容
using (FileStream fileStream = new FileStream(path, FileMode.Append))
{
byte[] data = Encoding.Default.GetBytes(content);
fileStream.Write(data, , data.Length);
}
//读文件
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
byte[] data = new byte[fileStream.Length];
fileStream.Read(data, , data.Length);
string result = Encoding.Default.GetString(data);
//do something...
} #endregion #region StreamWriter&StreamReader-StreamReader实现了抽象基类TextReader类,而StreamWriter实现了抽象基类TextWriter,分别用于对流的读取与写入 //写文件
using (StreamWriter streamWriter = new StreamWriter(path))
{
//方法一
streamWriter.Write(content);
streamWriter.Flush();//将缓冲区内容写入磁盘
//使用using就不必显示的关闭流,它会自动关闭并释放
//streamWriter.Close();
//方法二
streamWriter.WriteLine(content.ToCharArray());//按行写入
//streamWriter.Flush();
}
//追加内容
using (StreamWriter streamWriter = new StreamWriter(path, true))
{
//方法一
streamWriter.Write(content);
streamWriter.Flush();
//方法二
streamWriter.WriteLine(content.ToCharArray());//按行追加
}
//读文件(StreamReader类似指针位移的操作,所以实例化多个对象)
using (StreamReader streamReader_ToLine = new StreamReader(path))
using (StreamReader streamReader_ToEnd = new StreamReader(path))
using (StreamReader streamReader_To = new StreamReader(path))
{
string msg = String.Empty;
//方法一
while (!streamReader_ToLine.EndOfStream)
{
msg = streamReader_ToLine.ReadLine();
//do something...
}
//方法二
if (!streamReader_ToEnd.EndOfStream)
{
msg = streamReader_ToEnd.ReadToEnd();
//do something...
}
//方法三
char[] data = new char[streamReader_To.BaseStream.Length];
streamReader_To.Read(data, , data.Length);
string result = new String(data);
//do something...
} #endregion
上一篇:MySQL5.6 Waiting for Commit Lock


下一篇:Linux LVM使用小记