C#读取和写入文件(干货分享)
一、读取文件
读取的文件内容不多:
- 可以使用 File.ReadAllText(FilePath)
- 可以指定编码方式 File.ReadAllText(FilePath, Encoding)的方法。
- 可以使用File.ReadAllLines(FilePath)
- 可以指定编码方式File.ReadAllLines(FilePath, Encoding)的方法
这些方法都是一次将文本内容全部读完,
前两种方法返回一个包含全部文本内容的字符串;
后两种返回一个字符串数组,每一行都是一个数组元素。
如何使用:
string str = File.ReadAllText(@"c:\temp\ascii.txt");//第一种
string str2 = File.ReadAllText(@"c:\temp\ascii.txt", Encoding.ASCII);//第二种string[] strs = File.ReadAllLines(@"c:\temp\ascii.txt"); //第三种
string[] strs2 = File.ReadAllLines(@"c:\temp\ascii.txt", Encoding.ASCII);//第四种
读取的文件内容较多:
我们就不要将文本内容一次读完,而应该采用流(Stream)的方式来读取内容。.Net为我们封装了StreamReader类。初始化StreamReader类有很多种方式。
- 可以使用StreamReader(FilePath)
- 可以指定编码方式 StreamReader(FilePath, Encoding)
- 可以使用StreamReader(FileStream)
- 可以指定编码方式StreamReader(FileStream, Encoding)
- 可以使用File.OpenText(FilePath)
- 可以使用FileInfo.OpenText()
如何使用:
StreamReader sr1 = new StreamReader(@"c:\temp\utf-8.txt"); //第一种
StreamReader sr2 = new StreamReader(@"c:\temp\utf-8.txt", Encoding.UTF8);//第二种FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.Open, FileAccess.Read, FileShare.None); //初始化FileStream
StreamReader sr3 = new StreamReader(fs); //第三种
StreamReader sr4 = new StreamReader(fs, Encoding.UTF8);//第四种FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt"); //初始化FileInfo
// OpenText 创建一个UTF-8 编码的StreamReader对象
StreamReader sr5 = myFile.OpenText();//第五种
StreamReader sr6 = File.OpenText(@"C:\temp\utf-8.txt");//第六种
初始化完成之后,你可以每次读一行,也可以每次读一个字符 ,还可以每次读几个字符,甚至也可以一次将所有内容读完。
// 读一行
string nextLine = sr.ReadLine();
// 读一个字符
int nextChar = sr.Read();
// 读100个字符
int nChars = 100;
char[] charArray = new char[nChars];
int nCharsRead = sr.Read(charArray, 0, nChars);
// 全部读完
string restOfStream = sr.ReadToEnd();
//使用完StreamReader之后,关闭它:
sr.Close();
假如我们需要一行一行的读,将整个文本文件读完,下面看一个完整的例子:
StreamReader sr = File.OpenText(@"C:\temp\ascii.txt");
string nextLine;
while ((nextLine = sr.ReadLine()) != null)
{ Console.WriteLine(nextLine);
}
sr.Close();
二、写入文件
写入的文件内容不多:
- 可以使用File.WriteAllText(FilePath,String)
- 可以指定编码方式File.WriteAllText(FilePath, String,Encoding)
- 可以使用File.WriteAllLines(FilePath,String[])
- 可以指定编码方式File.WriteAllLines(FilePath,String[],Encoding)
前面两种写入的是一个字符串,后面两种写入的是一个字符串数组。
使用File.WriteAllText或File.WriteAllLines方法时,如果指定的文件路径不存在,会创建一个新文件;如果文件已经存在,则会覆盖原文件。
string str1 = "Good Morning!";//需要写入的字符串File.WriteAllText(@"c:\temp\test\ascii.txt", str1);//第一种File.WriteAllText(@"c:\temp\test\ascii-2.txt", str1, Encoding.ASCII);//第二种string[] strs = { "Good Morning!", "Good Afternoon!" };//需要写入的字符串数组File.WriteAllLines(@"c:\temp\ascii.txt", strs);//第三种File.WriteAllLines(@"c:\temp\ascii-2.txt", strs, Encoding.ASCII);//第四种
写入的文件内容较多:
同样也要使用流(Stream)的方式写入。.Net封装的类是StreamWriter。
初始化StreamWriter类同样有很多方式:
- 可以使用StreamWriter(FilePath)
- 可以指定编码方式 StreamWriter(FilePath, bool append,Encoding)
- 可以使用FileStream(FileStream);
- 可以指定编码方式StreamWriter(FileStream, Encoding)
- 可以使用File.CreateText(FilePath)
- 可以使用FileInfo.CreateText()
// 如果文件不存在,创建文件; 如果存在,覆盖文件
StreamWriter sw1 = new StreamWriter(@"c:\temp\utf-8.txt"); //第一种
// 也可以指定编码方式
// true 是 append text, false 为覆盖原文件
StreamWriter sw2 = new StreamWriter(@"c:\temp\utf-8.txt", true, Encoding.UTF8);//第二种// FileMode.CreateNew: 如果文件不存在,创建文件;如果文件已经存在,抛出异常
FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read);
// UTF-8 为默认编码
StreamWriter sw3 = new StreamWriter(fs); //第三种
StreamWriter sw4 = new StreamWriter(fs, Encoding.UTF8);//第四种// 如果文件不存在,创建文件; 如果存在,覆盖文件
FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt");
StreamReader sr6 = File.CreateText(@"C:\temp\utf-8.txt");//第五种
StreamWriter sw5 = myFile.CreateText();//第六种
初始化完成后,可以用StreamWriter对象一次写入一行,一个字符,一个字符数组,甚至一个字符数组的一部分。
// 写一个字符
sw.Write('a');// 写一个字符数组
char[] charArray = new char[100];
// initialize these characters
sw.Write(charArray);// 写一个字符数组的一部分
sw.Write(charArray, 10, 15);//使用完后关闭它
sw.Close();
最后来看一个完整的使用StreamWriter一次写入一行的例子:
FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt");
StreamWriter sw = myFile.CreateText();string[] strs = { "早上好", "下午好" };
foreach (var s in strs)
{ sw.WriteLine(s);
}
sw.Close();
C#读取和写入文件(干货分享)相关推荐
- 读取和写入文件的最简单方法
本文翻译自:Easiest way to read from and write to files There are a lot of different ways to read and writ ...
- sublime python3中读取和写入文件时如何解决编码问题
sublime python3中读取和写入文件时如何解决编码问题 参考文章: (1)sublime python3中读取和写入文件时如何解决编码问题 (2)https://www.cnblogs.co ...
- java写入文件编码格式为ansi_Java读取、写入文件如何解决乱码问题
读取文件流时,经常会遇到乱码的现象,造成乱码的原因当然不可能是一个,这里主要介绍因为文件编码格式而导致的乱码的问题.首先,明确一点,文本文件与二进制文件的概念与差异. 文本文件是基于字符编码的文件,常 ...
- Flutter进阶—读取与写入文件
Flutter使用path_provider插件读取与写入文件,path_provider插件提供了一种平台无关的方法来访问设备文件系统上常用的位置.该类目前支持访问两个文件系统位置: 临时目录:系统 ...
- nodejs:fs (内置模块)读取和写入文件
node fs (内置模块)读取和写入文件 const fs = require("fs"); //异步读取文件 fs.readFile("data.txt", ...
- go语言逐行读取和写入文件
前言 前面一篇博客讲到nodejs使用readline逐行读取和写入文件 今天使用go语言实现从输入文件中读取每行数据,然后将每行字段组合成SQL插入脚本,然后逐行写入另外一个空白文件中. tb_pa ...
- HttpWebRequest FileStream分块读取和写入文件WebClient
//HttpWebRequest 下载文件 private void DownloadFile(string filePath) { string[] ...
- python读取写入文件_Python读取和写入文件
1 从文件中读取数据 1.1 读取整个文件 创建名为test的txt文本文件,添加内容如下所示: 1234567890 2345678901 3456789012 实现代码: with open('t ...
- java读取与写入_Java读取与写入文件
import java.io.*; /** * 文件另存为的编码要选择UTF-8 */ public class RWFile { /** * @param path 文件的路径 */ public ...
最新文章
- 假如计算机是中国人发明的,那代码应该这么写
- Android实现RecyclerView侧滑删除和长按拖拽-ItemTouchHelper
- grunt入门讲解1:grunt的基本概念和使用
- iOS下JS与OC互相调用(六)--WKWebView + WebViewJavascriptBridge
- python中for循环的用法_浅谈Python的for循环
- php多态性和继承是什么意思,封装 继承 多态的区别
- vue watch第一次监听不到_Vue 的 computed 和 watch 的区别
- RecordAccumulator分析
- IOS开发-关于自定义TabBar条
- [Linux] DSO missing from command line
- Ubuntu图标变成问号
- java实战项目教程
- mssql数据库置疑修复
- ExpandableListView 的使用
- 7张图告诉你成功者与失败者的行为差别
- groupby分组聚合和运算2
- 栈与队列的相同点和不同点
- 关于基于kangle和EP面板使用CDN
- 大数据学习笔记之一:Hadoop 常用指令集合与启动注意项
- 计算机怎么格式化硬盘,电脑怎么格式化硬盘