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 文件流
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//更改路径字符串的后缀名,不会修改实际的文件
string newPath=
Path.ChangeExtension(@"D:\1.txt","avi");
MessageBox.Show("成功"+newPath);
}
private void button2_Click(object sender, EventArgs e)
{
//1创建1个文件流对象,并给这个文件流对象指定操作的文件路径和操作方式
FileStream stream = new
FileStream(@"D:\2.txt", FileMode.Open);
//2.准备一个byte数组以供文件流对象读取数据并放到这个数组里
byte[] buffer = new byte[1024 * 1024];
//3.调用文件流的读数据方法,将读取出来的字节放到buffer数组里
stream.Read(buffer, 0,
buffer.Length);
//4.将字节数组以指定的编码转换为字符串
string content =
Encoding.Default.GetString(buffer);
textBox1.Text = content;
//5.关闭文件流
stream.Dispose();//内部会自动调用Close()方法
}
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if
(sfd.ShowDialog() == DialogResult.OK)
{
//1.创建文件流对象
FileStream stream = new
FileStream(sfd.FileName,FileMode.Create);
//2.调用文件流写入的方法
string content = textBox1.Text;
//3.将字符串以指定的编码转换为字节数组(二进制)
byte[] buffer =
Encoding.UTF8.GetBytes(content);
//调用文件流对象的写入方法
stream.Write(buffer,0,buffer.Length);
stream.Dispose();
}
}
private void button4_Click(object sender, EventArgs e)
{
//1.准备个用于读取数据的文件流
FileStream streamReader = new
FileStream(@"D:\XX.avi", FileMode.Open);
//2.准备1个用于写数据的文件流
FileStream streamWriter = new
FileStream(@"E:\XX.avi",FileMode.Create);
//3.准备一个字节数组用于保存读出来的数据
byte[] data = new byte[1024*1024*2];
//4.用读的文件流将数据读出来,放到字节数组中
int lenght = 0;
do{
lenght = streamReader.Read(data, 0, data.Length);
streamWriter.Write(data, 0, lenght);
}while(lenght>=data
.Length);
streamReader.Dispose();
streamWriter.Dispose();
}
}
}
原文:http://www.cnblogs.com/sumg/p/3743987.html