当前位置:网站首页>C#(三十八)之StreamWriter StreamWriter使用方法及与FileStream类的区别
C#(三十八)之StreamWriter StreamWriter使用方法及与FileStream类的区别
2022-07-20 23:23:00 【camellias_】
StreamReader类的属性:
CurrentEncoding:获取流使用的字符编码
EndOfStream:指示当前位置是否在流的末尾
StreamReader类的方法:
Read():读取流中的下一个字符或下一组字符。
ReadBlock():读取一个字符块。
ReadLine():从流中读取一行字符
ReadToEnd():从流的当前位置读取到流的末尾
Close():关闭当前流,并释放资源
StreamWriter类的属性:
Ecoding:获取被写入类型的字符编码
例:outFile = new StreamWriter (“c://abc.txt”,false,Encoding.GetEncoding(“gb2312”));
NewLine:当前流使用“行结束符”;
StreamWriter类的方法:
Write():写入数据
WriteLine():写入数据,并添加行结束符
Close():关闭当前流,并释放资源
StreamXXXX类与FileStream类的区别:
1:StreamReader/StreamWriter操作的是字符数据(char),而FileStream操作的是字节数据(byte):
2:StreamXXXX类常用于文本的打开与保存,而FileStream则用于数据的传输。
3:FileStream是不能指定编码(因为它看到的只是文件的二进制形式,当然无所谓编码),所以如果有中文的文本的话需要转码。
4:FileStream是一个较底层的类,只能简单地读文件到而缓冲区,而StreamXXXX类封装了一些高级的方法,如ReadLine() (按行读取)
5:FileStream类主要使用于大文件读写,StreamXXXXX类主要用于小文件的读写。
StreamReader
/// <summary>
/// StreanReader读取
/// </summary>
private void button3_Click(object sender, EventArgs e)
{
path = textBox1.Text;
if (path != "" && File.Exists(path))
{
try
{
reader = new StreamReader(path, Encoding.Default);
string str = reader.ReadToEnd();
MessageBox.Show(str);
}
catch (Exception qq)
{
MessageBox.Show(qq.Message);
}
finally
{
// 关闭文件流
reader.Close();
// 关闭资源
reader.Dispose();
}
}
else
{
MessageBox.Show("请输入正确的路径");
return;
}
}
StreamWriter
/// <summary>
/// StreamWrite写入
/// </summary>
private void button4_Click(object sender, EventArgs e)
{
path = textBox1.Text;
try
{
if (path != "" && File.Exists(path))
{
//创建文件
//writer = File.CreateText(path);
writer = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
string contact = @"十年征战梦一场,功名利禄终相忘";
writer.Write(contact);
MessageBox.Show("写入成功!");
}
else
{
MessageBox.Show("请输入正确的路径");
return;
}
}
catch (Exception qq)
{
MessageBox.Show(qq.Message);
}
finally
{
writer.Close();
writer.Dispose();
}
}
测试使用全部代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace FileStreams
{
public partial class Form1 : Form
{
/// <summary>
/// 构造函数
/// </summary>
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 窗体加载事件
/// </summary>
private void Form1_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 定义一个FileStream类
/// </summary>
public FileStream ff = null;
/// <summary>
/// 存储文件路径
/// </summary>
public string path = "";
/// <summary>
/// StreamReader空对象
/// </summary>
public StreamReader reader = null;
/// <summary>
/// StreamWriter空对象
/// </summary>
public StreamWriter writer = null;
/// <summary>
/// FileStream读取
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
path = textBox1.Text;
if (path != "" && File.Exists(path))
{
ff = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
}
else
{
MessageBox.Show("请输入正确的路径");
return;
}
try
{
byte[] buffer = new byte[1024 * 1024 * 2]; //定义一个2M的字节数组
//返回本次实际读取到的有效字节数
int r = ff.Read(buffer, 0, buffer.Length); //每次读取2M放到字节数组里面
//将字节数组中每一个元素按照指定的编码格式解码成字符串
string sss = Encoding.Default.GetString(buffer, 0, r);
MessageBox.Show(sss);
}
catch (Exception qq)
{
MessageBox.Show(qq.Message);
}
finally
{
// 关闭文件流
ff.Close();
// 关闭资源
ff.Dispose();
}
}
/// <summary>
/// FileStream写入
/// </summary>
private void button2_Click(object sender, EventArgs e)
{
path = textBox1.Text;
try
{
if (path != "")
{
ff = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
string content = @"大漠孤烟直,长河落日圆";
// 将字符串读入字节数组中。
byte[] buffer = Encoding.Default.GetBytes(content);
// 将数组写入文件
ff.Write(buffer, 0, buffer.Length);
MessageBox.Show("写入成功");
}
else
{
MessageBox.Show("请输入正确的路径");
return;
}
}
catch (Exception qq)
{
MessageBox.Show(qq.Message);
}
finally
{
ff.Close();
ff.Dispose();
}
}
/// <summary>
/// StreanReader读取
/// </summary>
private void button3_Click(object sender, EventArgs e)
{
path = textBox1.Text;
if (path != "" && File.Exists(path))
{
try
{
reader = new StreamReader(path, Encoding.Default);
string str = reader.ReadToEnd();
MessageBox.Show(str);
}
catch (Exception qq)
{
MessageBox.Show(qq.Message);
}
finally
{
// 关闭文件流
reader.Close();
// 关闭资源
reader.Dispose();
}
}
else
{
MessageBox.Show("请输入正确的路径");
return;
}
}
/// <summary>
/// StreamWrite写入
/// </summary>
private void button4_Click(object sender, EventArgs e)
{
path = textBox1.Text;
try
{
if (path != "" && File.Exists(path))
{
//创建文件
//writer = File.CreateText(path);
writer = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
string contact = @"十年征战梦一场,功名利禄终相忘";
writer.Write(contact);
MessageBox.Show("写入成功!");
}
else
{
MessageBox.Show("请输入正确的路径");
return;
}
}
catch (Exception qq)
{
MessageBox.Show(qq.Message);
}
finally
{
writer.Close();
writer.Dispose();
}
}
}
}
有好的建议,请在下方输入你的评论。
欢迎访问个人博客
https://guanchao.site
欢迎访问小程序:
边栏推荐
- Practice - how many threads are appropriate to create
- JS-数组
- Starbucks CEO said that more stores may be closed to ensure the safety of employees
- 带你认识一下数仓的分区自动管理
- OpenCV学习——ArUco模块
- 整理的burp官网的漏洞语句
- 最新微服务组件选型
- Traverse the pictures of folders and subfolders, use OpenCV to change the size and save to a folder
- Analysis of tars source code 23
- 进程控制块(PCB) 包含哪些信息
猜你喜欢
进程控制块(PCB) 包含哪些信息
MySQL explain execution plan analysis
已解决Module not found: Error: Can‘t resolve ‘core-js/fn/reflect‘ in
二叉树的三种层序遍历BFS
模块学习(五)——矩阵键盘
同城多数据中心部署 TiDB
竣达技术丨MOBUS 转SNMP网络监控终端
卷积神经网络单图超分辨率的深度学习方法
Starbucks CEO said that more stores may be closed to ensure the safety of employees
Power Bi ---- slicer to make the report more beautiful
随机推荐
对等网主机的通信过程以及原理,很简单
JS operators and expressions \ flow structure of functions and programs
最新微服务组件选型
30岁被公司裁员,有人从此一蹶不振,而我逆风翻盘,重获新生~
@RequestParam注解的正确使用方式
How to analyze and design performance test scenarios
Interview must ask, how to ensure the idempotency of the interface?
Deep learning method of convolutional neural network single image super-resolution
Analysis of tars source code 24
MD编辑器 - Typora
YOLOv5改进之二:添加CBAM注意力机制
Huawei wireless devices are configured with ACL based message filtering
Message queue rocket Foundation
php-fpm自定义zabbix监控
SAP Fiori topic 2: using webide to build Fiori with navigation bar
Jmeter-正则、xpath、JSON
星巴克CEO称可能关闭更多店面以保证员工安全
静态通讯录的实现
Is there a completely independent localization database technology
迁移Repo管理的代码到Gerrit