在做winform简易文件处理器时需要从系统资源中读取和创建txt文件,不多说,具体方法如下,注意完整的文件路径,比如:C:\Users\86159\Documents\记事本txt文件\聪敏人傻子和奴才-鲁迅.txt
private void createFile(string fullPath, string content) //参数:文件路径,文本内容
{
FileStream file = File.OpenWrite(fullPath); //打开一个现有文件或创建一个文件来写入
StreamWriter writer = new StreamWriter(file); //创建写入流
writer.WriteLine(content); //写入数据
writer.Flush(); //清理写入器的缓冲区
writer.Close(); //关闭写入器
Console.WriteLine("文件保存成功!");
}
//文件读取方法
private string readFile(string fullPath) //传入参数:文件路径
{
FileStream file = File.OpenRead(fullPath); //打开现有问价进行读操作
StreamReader reader = new StreamReader(file); //创建读取流
string content = "";
content = reader.ReadToEnd(); //从file中读数据
reader.Dispose(); //释放reader占用的file资源
reader.Close(); //关闭文件读取器
Console.WriteLine("文件读取成功!");
return content; //返回文本内容
}
}
}
顺带将OpenFIleDialog&SaveFileDialog用法记录一下:
//打开
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "请选择文件(.txt):"; //设置对话框标题
openFileDialog.Filter = "(*.txt)|*.txt"; //设置文件类型。不设置默认打开上次路径
openFileDialog.InitialDirectory = startPath; //设置打开初始目录
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
fullPath = openFileDialog.FileName; //文件全路径
fileName = fullPath.Substring(fullPath.LastIndexOf("\\") + 1); //文件名和后缀
startPath = fullPath.Substring(0,fullPath.LastIndexOf("\\")); //获取文件路径
Console.WriteLine("fullPath = " + fullPath);
Console.WriteLine("fileName = " + fileName);
Console.WriteLine("startPath = " + startPath);
text = readFile(fullPath); //调用readFile方法
Console.WriteLine(fileName+"的内容:\n"+text);
richTextBox1.Text = text; //更新富文本框内容
}
}
//保存
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "(*.txt)|*.txt"; //设置保存类型
save.Title = "请选择保存位置和文件名"; //对话框标题
save.InitialDirectory = startPath; //设置初始打开目录
if (save.ShowDialog() == DialogResult.OK)
{
fullPath = save.FileName;
fileName = fullPath.Substring(fullPath.LastIndexOf("\\") + 1); //文件名
startPath = fullPath.Substring(0, fullPath.LastIndexOf("\\")); //改写初始文件路径
Console.WriteLine("fileName = "+fileName);
Console.WriteLine("startPath = " + startPath);
createFile(fullPath, text); //调用createFile方法创建txt文件
}
}
StreamWriter 类的方法:
bool AutoFlush | 属性,获取或设置是否自动刷新缓冲区 |
Encoding Encoding | 只读属性,获取当前流中的编码方式 |
void Close() | 关闭流 |
void Flush() | 刷新缓冲区 |
void Write(char value) | 将字符写入流中 |
void WriteLine(char value) | 将字符换行写入流中 |
Task WriteAsync(char value) | 将字符异步写入流中 |
Task WriteLineAsync(char value) | 将字符异步换行写入流中 |
StreamReader 类的方法:
Encoding CurrentEncoding | 只读属性,获取当前流中使用的编码方式 |
bool EndOfStream | 只读属性,获取当前的流位置是否在流结尾 |
void Close() | 关闭流 |
int Peek() | 获取流中的下一个字符的整数,如果没有获取到字符, 则返回 -1 |
int Read() | 获取流中的下一个字符的整数 |
int Read(char[] buffer, int index, int count) | 从指定的索引位置开始将来自当前流的指定的最多字符读到缓冲区 |
string ReadLine() | 从当前流中读取一行字符并将数据作为字符串返回 |
string ReadToEnd() | 读取来自流的当前位置到结尾的所有字符 |