15.WinForm练习--打开文件对话框

namespace _15.打开文件对话框
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    private void button1_Click(object sender, EventArgs e)
    {
        //点击弹出对话框,新建对话框对象
        OpenFileDialog ofd = new OpenFileDialog();
        //设置对话框标题
        ofd.Title = "请选择要打开的文件";
        //可以对文件进行多选
        ofd.Multiselect = true;
        //设置对话框初始目录
        ofd.InitialDirectory = @"C:\Users\Administrator.USER-20180925HC\Desktop\pic";
        //设置对话框的文件类型
        ofd.Filter = "文本文件|*.txt|媒体文件|*.wav|图片文件|*.jpg|所有文件|*.*";
        //展示对话框
        ofd.ShowDialog();

        //获取打开对话框选中文件路径
        string path = ofd.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);
            //解析buffer数组
            textBox1.Text=Encoding.Default.GetString(buffer, 0, r);
        }

    }
}

}

猜你喜欢

转载自blog.51cto.com/12679593/2398756