直接贴出可以使用的代码:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
//1.实例化 打开文件对话框对象
//2.Filter设置,FilterIndex 从1开始
openFileDialog1.Filter = "txt files (*.txt)| *.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
//打开对话框,有打开文件时执行
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string name = openFileDialog1.FileName;//获取文件名
string str = File.ReadAllText(name);//获取所有的txt
//------------依据要求处理------------------------------------
//--此处读取以空格为间隔的一串数据-----------------------------
//--
string[] pieces1 = str.Split(' '); //用空格截取字符串
List<string> pieces2 = new List<string>();//创建字符串链表
foreach (string str1 in pieces1)
{
if (str1 == "" || str1 == "\n") //str1为空时不存储
{
continue;
}
else //存储有效的数据
{
pieces2.Add(str1);
}
}
string[] pieces = pieces2.ToArray();//如有需要,拷贝至字符串数组
}
}
其它设置:
openFileDialog1.InitialDirectory = “C:\”; //设置初始路径
openFileDialog1.RestoreDirectory = true; //是否保存路径