C#复习(十八)文件读写操作
对文件的读写操作可通过以下三个类来进行:
二、StreamWriter、StreamReader类
- File
- StreamWriter、StreamReader
- FileStream
一、File类
string path
= @"F:\FCJ\haha.txt";
- 创建文件:
if
(!File.Exists(path))
File.Create(path);
- 重写文件内容File.WriteAllText():不能和Create一起使用,否则会报异常,路径不存在会报错,文件不存在会自动创建,存在的话之前的内容会清空
File.WriteAllText(path, "今天C#复习结束~~~");
string
info1 = File.ReadAllText(path);
Console.WriteLine(info1);
- 追加文件内容File.AppendAllText():不能和Create一起使用,否则会报异常。路径不存在会报错,文件不存在会自动创建
File.AppendAllText(path, "嘻嘻");
string
info2 = File.ReadAllText(path);
Console.WriteLine(info2);
- 删除文件
File.Delete(path);
string
path = @"F:\FCJ\haha.txt";
- 写入文件:文件不存在会自动创建,存在的话之前的内容会清空
StreamWriter sw = new StreamWriter(path);
sw.Write(@"通过StreamWriter进行写操作,
通过StreamWriter进行写操作,
通过StreamWriter进行写操作");
sw.Close();
- 读取文件:文件不存在会报错
if
(File.Exists(path))
{
StreamReader sr = new
StreamReader(path);
string str;
while ((str = sr.ReadLine())
!= null)
Console.WriteLine(str);
}
三、FileStream类
- Encoder可以将一组字符编码为一个字节序列。而Decoder可以将已编码的字节序列解码为字符序列。
- Encoder 编码:在网络传输和文件操作中,如果数据量很大,需要将其划分为较小的快,此时可能出现一个数据块的末尾是一个不匹配的高代理项,而与其匹配的低代理项在下一个数据块。 这时候使用Encoding的GetBytes方法处理较为麻烦,我们直接使用Encoder处理。
- Decoder 解码: 用于将原始字节转换为更有用的项,比如字符。
string
path = @"F:\FCJ\haha.txt";
- 文件写入:
using
(FileStream fs_writer = new FileStream(path,
FileMode.Create))
{
byte[] bytes =
Encoding.Default.GetBytes("通过FileStream进行文件读写");
fs_writer.Write(bytes, 0,
bytes.Length);
fs_writer.Flush();
fs_writer.Close();
}
- 文件读取:(两种方法)
using
(FileStream fs_reader = new FileStream(path, FileMode.Open))
{
byte[] newbytes = new
byte[1024];
char[] chars = new
char[1024];
fs_reader.Seek(0,
SeekOrigin.Begin);
fs_reader.Read(newbytes, 0,
newbytes.Length);
Decoder d =
Encoding.Default.GetDecoder();
d.GetChars(newbytes, 0,
newbytes.Length, chars, 0);
Console.WriteLine(chars);
}
using
(FileStream fs_reader = new FileStream(path, FileMode.Open))
{
byte[] newbytes = new
byte[1024];
fs_reader.Seek(0,
SeekOrigin.Begin);
fs_reader.Read(newbytes, 0,
newbytes.Length);
string info =
Encoding.Default.GetString(newbytes);
Console.WriteLine(info);
Console.ReadKey();
}