C#读写文件|遍历文件|打开保存文件

本文示例源代码及窗体设计详见:http://download.csdn.net/source/3431745      

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 FileReadWriteDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //遍历文件 - 浏览按钮
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.*)|*.*";                //过滤文件类型
            ofd.RestoreDirectory = true; //记忆上次浏览路径
            if(ofd.ShowDialog() == DialogResult.OK)
            {
                DirectoryInfo dir = Directory.GetParent(ofd.FileName);   //获取文件所在的父目录
                textBox1.Text = dir.ToString()+"\\";
            }
        }
        //遍历文件 - 遍历按钮
        private void buttonTransform_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            TransformFiles(textBox1.Text.Trim());
        }

        public void TransformFiles(string path)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                DirectoryInfo[] dirs = dir.GetDirectories();  //获取子目录
                FileInfo[] files = dir.GetFiles("*.*");  //获取文件名
                foreach (DirectoryInfo d in dirs)
                {
                    TransformFiles(dir+d.ToString()+"\\"); //递归调用
                }
                foreach(FileInfo f in files)
                {
                    listBox1.Items.Add(dir+f.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }           
        }

        //打开保存 - 打开按钮
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            textBox3.Text = "";
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.txt)|*.txt|(*.*)|*.*";
            ofd.RestoreDirectory = true;
            if(ofd.ShowDialog() == DialogResult.OK)
            {               
                textBox2.Text = ofd.FileName;
                FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                try
                {
                    ofd.OpenFile(); //打开文件
                    string line = sr.ReadLine(); //读取文本行
                    while (line != null)
                    {
                        textBox3.Text += line + "\n";  //换行后继续读取直至line==null
                        line = sr.ReadLine();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                finally
                {
                    sr.Close();
                    fs.Close();
                }
            }

        }

        //打开保存 - 保存按钮
        private void buttonSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "(*.txt)|*.txt|(*.*)|*.*";
            sfd.AddExtension = true;
            sfd.RestoreDirectory = true;
            if(sfd.ShowDialog() == DialogResult.OK)
            {
                textBox2.Text = sfd.FileName;
                FileStream fs = new FileStream(sfd.FileName,FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                try
                {
                    sw.Write(textBox3.Text);
                    sw.Flush();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                finally
                {
                    sw.Close();
                    fs.Close();
                }
            }
        }

        //读写文本 - 写入数据按钮
        private void buttonWrite_Click(object sender, EventArgs e)
        {
            if (!(Directory.Exists(@"D:\temp")))
            {
                Directory.CreateDirectory(@"D:\temp");
            }
            string filePath = @"D:\temp\qq.doc";
            if(File.Exists(filePath))
            {
                labelResult.ForeColor = Color.Red;
                labelResult.Text = "当前文件已经存在!";
                return;
            }

            FileStream fs = new FileStream(filePath,FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            try
            {
                sw.Write(textBox4.Text);
                sw.Flush();
                labelResult.ForeColor = Color.Green;
                labelResult.Text = "写入数据完成!";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
        }

        //读写文本 - 读取数据按钮
        private void buttonRead_Click(object sender, EventArgs e)
        {
            textBox5.Text = "";
            string filePath = @"D:\temp\qq.doc";
            if(!(File.Exists(filePath)))
            {
                labelResult.ForeColor = Color.Red;
                labelResult.Text = filePath+"文件不存在!";
                return;
            }
            FileStream fs = new FileStream (filePath,FileMode.Open,FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            try
            {
                string line = sr.ReadLine();
                while(line != null)
                {
                    textBox5.Text += line + "\n";
                    line = sr.ReadLine();
                }
                labelResult.ForeColor = Color.Green;
                labelResult.Text = "读取数据成功!";
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                sr.Close();
                fs.Close();
            }
        }

        //读写二进制文件 - 写入数据按钮
        private void buttonWrite2_Click(object sender, EventArgs e)
        {
            string filePath = @"D:\temp\test.data";
            if (!(Directory.Exists(@"D:\temp")))
            {
                Directory.CreateDirectory(@"D:\temp");
            }           
            if(File.Exists(filePath))
            {
                labelResult2.ForeColor = Color.Red;
                labelResult2.Text = "文件已经存在!";
                return;
            }
            FileStream fs = new FileStream(filePath,FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);

            for (int i = 0; i < 200; i++)
            {
                bw.Write((int)i);
            }
            bw.Flush();
            labelResult2.ForeColor = Color.Green;
            labelResult2.Text = "写入数据成功!";
            bw.Close();
            fs.Close();
        }

        //读写二进制文件 - 读取数据按钮
        private void buttonRead2_Click(object sender, EventArgs e)
        {
            textBox6.Text = "";
            string filePath = @"D:\temp\test.data";
            if(!(File.Exists(filePath)))
            {
                labelResult2.ForeColor = Color.Red;
                labelResult2.Text = filePath+"文件不存在!";
                return;
            }
            FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            for (int i = 0; i < 200; i++)
            {
                Int32 intTmp = br.ReadInt32();
                textBox6.Text += "->" + intTmp.ToString();
            }
            labelResult2.ForeColor = Color.Green;
            labelResult2.Text = "读取数据成功!";
            br.Close();
            fs.Close();
        }

    }
}
本文示例源代码及窗体设计详见:http://download.csdn.net/source/3431745

你可能感兴趣的:(C#)