当前位置:编程学习 > C#/ASP.NET >>

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

本文示例源代码及窗体设计详见:/2012/0103/20120103011132369.rar


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.S

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,