//==================代码编辑===========================================
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;
}
}
/// <summary>
/// 选定某个文件夹下面的文本文件
/// </summary>
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;
}
}
/// <summary>
/// 保存文本文件
/// </summary>
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);
sw.Write(richTextBox1.Text);
TypeW = 0;
MessageBox.Show("已经成功的将文本文件写入" + textBox2.Text + "之中", "提示信息");
//注意:此处顺序绝不可调换,为什么?
sw.Close();
fs.Close();
}
}
}
}
}
|
本文出自 “熊猫写程序” 博客,转载请与作者联系!