C#读写文件、遍历文件、打开保存文件,窗体程序

简介: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.

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();
        }

    }
}

目录
相关文章
|
3月前
|
缓存 C# Windows
C#程序如何编译成Native代码
【10月更文挑战第15天】在C#中,可以通过.NET Native和第三方工具(如Ngen.exe)将程序编译成Native代码,以提升性能和启动速度。.NET Native适用于UWP应用,而Ngen.exe则通过预编译托管程序集为本地机器代码来加速启动。不过,这些方法也可能增加编译时间和部署复杂度。
200 2
|
14天前
|
C#
基于 C# 编写的 Visual Studio 文件编码显示与修改扩展插件
基于 C# 编写的 Visual Studio 文件编码显示与修改扩展插件
|
1月前
|
算法 Java 测试技术
Benchmark.NET:让 C# 测试程序性能变得既酷又简单
Benchmark.NET是一款专为 .NET 平台设计的性能基准测试框架,它可以帮助你测量代码的执行时间、内存使用情况等性能指标。它就像是你代码的 "健身教练",帮助你找到瓶颈,优化性能,让你的应用跑得更快、更稳!希望这个小教程能让你在追求高性能的路上越走越远,享受编程带来的无限乐趣!
108 13
|
3月前
|
存储 C#
【C#】大批量判断文件是否存在的两种方法效率对比
【C#】大批量判断文件是否存在的两种方法效率对比
59 1
|
3月前
|
设计模式 程序员 C#
C# 使用 WinForm MDI 模式管理多个子窗体程序的详细步骤
WinForm MDI 模式就像是有超能力一般,让多个子窗体井然有序地排列在一个主窗体之下,既美观又实用。不过,也要小心管理好子窗体们的生命周期哦,否则一不小心就会出现一些意想不到的小bug
292 0
|
3月前
|
API C# Windows
【C#】在winform中如何实现嵌入第三方软件窗体
【C#】在winform中如何实现嵌入第三方软件窗体
164 0
|
3月前
|
XML 存储 安全
C#开发的程序如何良好的防止反编译被破解?ConfuserEx .NET混淆工具使用介绍
C#开发的程序如何良好的防止反编译被破解?ConfuserEx .NET混淆工具使用介绍
163 0
|
3月前
|
安全 API C#
C# 如何让程序后台进程不被Windows任务管理器强制结束
C# 如何让程序后台进程不被Windows任务管理器强制结束
87 0
|
3月前
|
XML 存储 缓存
C#使用XML文件的详解及示例
C#使用XML文件的详解及示例
156 0
|
2月前
|
C# 开发者
C# 一分钟浅谈:Code Contracts 与契约编程
【10月更文挑战第26天】本文介绍了 C# 中的 Code Contracts,这是一个强大的工具,用于通过契约编程增强代码的健壮性和可维护性。文章从基本概念入手,详细讲解了前置条件、后置条件和对象不变量的使用方法,并通过具体代码示例进行了说明。同时,文章还探讨了常见的问题和易错点,如忘记启用静态检查、过度依赖契约和性能影响,并提供了相应的解决建议。希望读者能通过本文更好地理解和应用 Code Contracts。
44 3