在C#的System.IO命名空间中,FileStream类是用于操作文件流的主要类。以下是使用FileStream类的一些常见方法:
- 创建FileStream对象:可以使用构造函数来创建一个FileStream对象,并指定要打开的文件路径和打开方式(例如,读取、写入、追加等)。
- 读取文件:可以使用StreamReader或BinaryReader类来读取文件内容。在读取文件之前,需要将FileStream对象设置为读取模式。
- 写入文件:可以使用StreamWriter或BinaryWriter类来写入文件内容。在写入文件之前,需要将FileStream对象设置为写入模式。
- 关闭FileStream对象:完成文件操作后,需要关闭FileStream对象以释放资源。
FileStream类案例练习-使用不同的方式打开文件
创建一个Windows应用程序,使用不同的方式,打开文件,其中包含“读写方式打开”、“追加方式打开”、“清空后打开”、“覆盖方式打开”,然后对其进行读写操作,再添加一些相关按钮(TextButton、RadioButton、Button)。如图:
完整示例代码:
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 addfile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
FileMode fileM = FileMode.Open;//声明一个FileMode对象,用来记录要打开的方式
//执行读写操作
private void button1_Click(object sender, EventArgs e)
{
string path = textBox1.Text;//获取打开文件的路径
try
{
using (FileStream fs = File.Open(path, fileM))//以指定的方式打开文件
{
if (fileM != FileMode.Truncate)//如果在打开文件后不清空文件
{
Byte[] info = new UTF8Encoding(true).GetBytes(textBox2.Text);//将要添加的内容转换成字节
fs.Write(info, 0, info.Length);//向文件中写入内容
}
}
using (FileStream fs = File.Open(path, FileMode.Open))//以读/写方式打开文件
{
byte[] b = new byte[1024];//定义一个字节数组
UTF8Encoding temp = new UTF8Encoding(true);//实现UTF-8编码
string pp = "";
while (fs.Read(b, 0, b.Length) > 0)//读取文本中的内容
{
pp += temp.GetString(b);//累加读取的结果
}
MessageBox.Show(pp);//显示文本中的内容
}
}
catch//如果文件不存在,则发生异常
{
if (MessageBox.Show("该文件不存在,是否创建文件。", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)//显示提示框,判断是否创建文件
{
FileStream fs = File.Open(path, FileMode.CreateNew);//在指定的路径下创建文件
fs.Dispose();//释放流
}
}
}
//选择打开方式
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (((RadioButton)sender).Checked == true)//如果单选按钮被选中
{
switch (Convert.ToInt32(((RadioButton)sender).Tag.ToString()))//判断单选项的选中情况
{
//记录文件的打开方式
case 0: fileM = FileMode.Open; break;//以读/写方式打开文件
case 1: fileM = FileMode.Append; break;//以追加方式打开文件
case 2: fileM = FileMode.Truncate; break;//打开文件后清空文件内容
case 3: fileM = FileMode.Create; break;//以覆盖方式打开文件
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}