一、 打開文件或文件夾加載數據
1. 定義一個列表用來接收路徑
public List< string > paths = new List< string > ( ) ;
2. 打開文件選擇一個文件并將文件放入列表中
OpenFileDialog open = new OpenFileDialog ( ) ;
open. Filter = "(*.jpg;*.jpge;*.bmp;*.png)|*.jpg;*.jpge;*.bmp;*.png" ;
open. Title = "請選擇一個文件" ;
string path = "" ;
if ( open. ShowDialog ( ) == DialogResult. OK)
{ paths. Clear ( ) ; path = open. FileName; paths. Add ( path) ;
}
3. 打開一個文件夾并選擇一個文件夾再將文件夾中的目錄放入列表中
FolderBrowserDialog files = new FolderBrowserDialog ( ) ;
files. Description = "請選擇文件夾" ;
string filePath = "" ;
if ( files. ShowDialog ( ) == DialogResult. OK) { paths. Clear ( ) ; filePath = files. SelectedPath; DirectoryInfo filePaths = new DirectoryInfo ( filePath) ; FileInfo[ ] fileData = filePaths. GetFiles ( ) ; foreach ( FileInfo file in fileData) { paths. Add ( file. FullName) ; }
}
4. 每次調用都可以獲取列表中的一個文件
public int num = 0 ;
private string GetPath ( )
{ num++ ; if ( num > paths. Count - 1 ) { num = 0 ; } return paths[ num] ;
}
二、封裝
using System ;
using System. Collections. Generic ;
using System. IO ;
using System. Linq ;
using System. Text ;
using System. Threading. Tasks ;
using System. Windows. Forms ; namespace VP與C_連接
{ internal class MyFileSelection { public List< string > paths = new List< string > ( ) ; public int num = 0 ; public string SelectionFile ( ) { OpenFileDialog open = new OpenFileDialog ( ) ; open. Filter = "(*.jpg;*.jpge;*.bmp;*.png)|*.jpg;*.jpge;*.bmp;*.png" ; open. Title = "請選擇一個文件" ; string path = "" ; if ( open. ShowDialog ( ) == DialogResult. OK) { paths. Clear ( ) ; path = open. FileName; paths. Add ( path) ; } return path; } public string SelectionFolder ( ) { FolderBrowserDialog files = new FolderBrowserDialog ( ) ; files. Description = "請選擇文件夾" ; string filePath = "" ; if ( files. ShowDialog ( ) == DialogResult. OK) { paths. Clear ( ) ; filePath = files. SelectedPath; DirectoryInfo filePaths = new DirectoryInfo ( filePath) ; FileInfo[ ] fileData = filePaths. GetFiles ( ) ; foreach ( FileInfo file in fileData) { paths. Add ( file. FullName) ; } } return filePath; } public string GetPath ( ) { num++ ; if ( num > paths. Count - 1 ) { num = 0 ; } return paths[ num] ; } }
}