天天看點

C#選擇多個檔案并讀取多個檔案資料

原文: C#選擇多個檔案并讀取多個檔案資料

版權聲明:本文為部落客原創文章,轉載請附上連結位址。 https://blog.csdn.net/ld15102891672/article/details/80586097

在程式設計工作中有時候會涉及到在檔案管理器中選擇多個檔案,點選确定後程式可以依次讀取所選檔案裡面的資料,那麼該怎麼實作呢?小博也是查閱了不少資料才獲得的經驗,下面小博以C#語言為例,附上一次讀取多個檔案的主要代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace ...
{
Class ...
{
 private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = true;//等于true表示可以選擇多個檔案
            dlg.DefaultExt = ".txt";
            dlg.Filter = "記事本檔案|*.txt";
            if (dlg.ShowDialog()==DialogResult.OK)
            {

                foreach (string file in dlg.FileNames)
                {
                    StreamReader sr = new StreamReader(file);
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                      //在此處添加需要對檔案中每一行資料進行處理的代碼
                    }
                    sr.Close();
                }
                
            }
        }
}

}