程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#讀寫文件|遍歷文件|打開保存文件

C#讀寫文件|遍歷文件|打開保存文件

編輯:C#入門知識

本文示例源代碼及窗體設計詳見:http://www.BkJia.com/uploadfile/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.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();
        }

    }
}

 摘自 白雲飄飄

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved