一、 打开文件或文件夹加载数据
1. 定义一个列表用来接收路径
public List<string> paths = new List<string>();
2. 打开文件选择一个文件并将文件放入列表中
OpenFileDialog open = new OpenFileDialog();
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.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];
}
}
}