文件流复习

本文详细介绍了如何使用C#中的FileStream类进行文件的读写操作,包括将字符串转换为字节数组并写入文件,以及从文件中读取字节数组并转换回字符串的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace _02文件流复习
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//使用File静态类实现写入
// File.WriteAllText(textBox1.Text.Trim(), textBox2.Text.Trim());
//使用FileStream类实现写入数据
using (FileStream fsWrite = File.OpenWrite(textBox1.Text.Trim()))
{
//1.把字符串转换为byte[]
byte[] buffer = Encoding.UTF8.GetBytes(textBox2.Text.Trim());

//写入数据
fsWrite.Write(buffer, 0, buffer.Length);
}
MessageBox.Show("ok");
}

private void button2_Click(object sender, EventArgs e)
{
//1.通过File来实现读取
//textBox2.Text = File.ReadAllText(textBox1.Text.Trim());

//2.通过FileStream实现读取
using (FileStream fsRead = File.OpenRead(textBox1.Text.Trim()))
{
byte[] buffer = new byte[fsRead.Length];
fsRead.Read(buffer, 0, buffer.Length);
textBox2.Text = Encoding.UTF8.GetString(buffer);
}
}
}
}

转载于:https://www.cnblogs.com/DJYBlog/p/4107617.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值