34.winform之打开文件对话框
效果
实现
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp4 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
//点击弹出对话框
OpenFileDialog openFileDialog = new OpenFileDialog();
//设置对话框的标题
openFileDialog.Title = "请选择要打开的文本文件";
//设置对话框可以多选
openFileDialog.Multiselect = false;
//设置对话框的初始目录
openFileDialog.InitialDirectory = @"C:\Users\22053\Desktop";
//设置对话框的文件类型
openFileDialog.Filter = "文本文件|*.txt|媒体文件|*.wmv|图片文件|*.png|所有文件|*.*";
//展示对话框
openFileDialog.ShowDialog();
////获得在打开的对话框中选中文件的路径
string path = openFileDialog.FileName;
if (path == "") {
return;
}
using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)) {
byte[] buffer = new byte[1024 * 1024 * 5];
//实际读取到的字节数
int r = fsRead.Read(buffer, 0, buffer.Length);
textBox1.Text = Encoding.Default.GetString(buffer, 0, r);
}
}
}
}
注意此处设置对话框的文件类型openFileDialog.Filter = "文本文件|*.txt|媒体文件|*.wmv|图片文件|*.png|所有文件|*.*";
效果如下: