本案例您将学习到:
n如何通过用户选择文件夹,获取文件夹信息。
n如何通过用户选择文件,获取文件信息。
n如何通过文件流建立一个新的文本文件。
n如何打开文本文件后重新写文本信息流。
n如何在C#中定义文件和文件夹。
n文件流的资源释放意义以及释放资源的基本顺序。
u实验步骤(1):
由图3-9所示,从工具箱之中拖拽三个GroupBox控件到Form窗体上,text属性分别设置为:“添加物理路径”、“打开文本文件”、“文本编辑区”;向第一个GroupBox控件拖拽一个TextBox控件;再向第一个GroupBox控件拖拽一个Button控件,text属性设置为“选定文件夹”;向第二个GroupBox控件拖拽一个TextBox控件;再向第二个GroupBox控件拖拽一个Button控件,text属性设置为“选定文件”;向第三个GroupBox控件拖拽一个richTextBox控件;再向窗体上非GroupBox区域拖拽一个Button控件,text属性设置为“保存文本文件”。
图3-9 文件操作案例2界面图
u实验步骤(2):
在类Form11里添加一个字段TypeW,int类型,代表人为的操作类型;用鼠标双击所有Button控件,进入.cs文件编辑状态准备进行开发。代码加下:
//==================代码编辑===========================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileOptionApplication
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}
//添加变量TypeW,int类型,0为默认,1为打开文件夹并建立new.txt文件,2为打开文本文件
int TypeW = 0;
/// <summary>
/// 选定某个文件夹
/// </summary>
private void button1_Click(object sender, EventArgs e)
//新建文件夹
FolderBrowserDialog openfolder = new FolderBrowserDialog();
if (openfolder.ShowDialog ()== DialogResult.OK)
{
textBox1.Text = Convert.ToString(openfolder.SelectedPath);
TypeW = 1;
}
/// 选定某个文件夹下面的文本文件
private void button4_Click(object sender, EventArgs e)
OpenFileDialog openfile = new OpenFileDialog();
openfile.Filter = "文本文件|*.txt";
if (openfile.ShowDialog() == DialogResult.OK)
FileStream OpenFileStream = new FileStream(openfile.FileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(OpenFileStream, Encoding.Default);
richTextBox1.Text = sr.ReadToEnd();
textBox2.Text = Convert.ToString(openfile.FileName);
OpenFileStream.Close();
sr.Close();
TypeW = 2;
/// 保存文本文件
private void button2_Click(object sender, EventArgs e)
if (richTextBox1.Text == string.Empty)
MessageBox.Show("编辑文本文件内容禁止为空!", "提示信息");
return;
else
if (TypeW == 1)
{
FileStream fs = new FileStream(textBox1.Text+@"\\new.txt",FileMode.Create,FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs,Encoding.Default);
sw.Write(richTextBox1.Text);
TypeW = 0;
MessageBox.Show("已经成功的将文本文件写入" + textBox1.Text + "\\new.txt之中","提示信息");
//注意:此处顺序绝不可调换,为什么?【另外,为什么必须关闭线程资源?】
sw.Close();
fs.Close();
}
else if(TypeW==2)
FileStream fs = new FileStream(textBox2.Text, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
MessageBox.Show("已经成功的将文本文件写入" + textBox2.Text + "之中", "提示信息");
//注意:此处顺序绝不可调换,为什么?
}
}
本文转自 qianshao 51CTO博客,原文链接:http://blog.51cto.com/qianshao/210966,如需转载请自行联系原作者