winform button 选择文件 OpenFileDialog
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string filetxt = textBox1.Text;
if (!File.Exists(filetxt))
{
MessageBox.Show("您要查找的文件不存在");
richTextBox1.Text = string.Empty;
return;
}
else
{
string result = string.Empty;
//文件实例化streamreader对象
StreamReader sr = new StreamReader(filetxt, Encoding.GetEncoding("gb2312"));
//调用readertoend 方法读取选中文件的全部内容
result = sr.ReadToEnd();
richTextBox1.Text = result;
//关闭当前文件读取流
sr.Close();
return ;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != "" && richTextBox1.Text != string.Empty)
{
string[] arry = richTextBox1.Text.Split('.');
richTextBox1.Text = string.Empty;
for (int i = 0; i <= arry.Length-1; i++)
{
richTextBox1.Text += arry[i];
}
}
else
{
MessageBox.Show("您要截取的数据不存在");
richTextBox1.Text = string.Empty;
return;
}
}
private void button3_Click(object sender, EventArgs e)
{
//初始化一个OpenFileDialog类
OpenFileDialog fileDialog = new OpenFileDialog();
//判断用户是否正确的选择了文件
if (fileDialog.ShowDialog() == DialogResult.OK)
{
//文件名
textBox1.Text = fileDialog.FileName;
string filetxt = textBox1.Text;
if (!File.Exists(filetxt))
{
MessageBox.Show("您要查找的文件不存在");
richTextBox1.Text = string.Empty;
return;
}
else
{
string result = string.Empty;
//文件实例化streamreader对象
StreamReader sr = new StreamReader(filetxt, Encoding.GetEncoding("gb2312"));
//调用readertoend 方法读取选中文件的全部内容
result = sr.ReadToEnd();
richTextBox1.Text = result;
//关闭当前文件读取流
sr.Close();
return;
}
//获取用户选择文件的后缀名
//string extension = Path.GetExtension(fileDialog.FileName);
//声明允许的后缀名
//string[] str = new string[] { ".gif", ".jpge", ".jpg" };
//if (!str.Contains(extension))
//{
//MessageBox.Show("仅能上传gif,jpge,jpg格式的图片!");
//}
//else
//{
////获取用户选择的文件,并判断文件大小不能超过20K,fileInfo.Length是以字节为单位的
//FileInfo fileInfo = new FileInfo(fileDialog.FileName);
//if (fileInfo.Length > 20480)
//{
//MessageBox.Show("上传的图片不能大于20K");
//}
//else
//{
////在这里就可以写获取到正确文件后的代码了
//}
}
// }
}
}
}