C#学习笔记之打开文件对话框

<span style="font-size:18px;">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 打开文件对话框
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 设置文本多行时自动换行
            textBox1.WordWrap = true;

            // 设置垂直滚动条
            textBox1.ScrollBars = ScrollBars.Vertical;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 创建一个打开文件对话框对象
            OpenFileDialog ofd = new OpenFileDialog();

            // 设置打开对话框的标题
            ofd.Title = "请选择文件:";

            // 打开文件对话框时是否显示“帮助”
            ofd.ShowHelp = true;

            // 是否允许选择多个文件
            ofd.Multiselect = true;

            // 获取或设置打开对话框时的初始目录
            ofd.InitialDirectory = @"D:\photo";

            // 设置对话框的文件类型
            ofd.Filter = "文本文件(*.txt;*.jpg)|*.txt;*.jpg|图片文件(*.jpg;*.bmp)|*.jpg;*.bmp";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                // 选择单个文件时,获取的文件的全路径
                string strPath = ofd.FileName;

                // 选中多个文件时,将所有文件的全路径存储在字符数组中
                string[] strPaths = ofd.FileNames;

                //MessageBox.Show(strPath);

                using (FileStream fsRead = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    byte[] buffer = new byte[fsRead.Length];

                    // 从选中的文件中读取数据,返回实际读取的字节数
                    int len = fsRead.Read(buffer, 0, buffer.Length);
                    //textBox1.Text = Encoding.UTF8.GetString(buffer, 0, len);
                    textBox1.Text = Encoding.Default.GetString(buffer, 0, len);
                }

                // 将光标移动到文本的最后,分为三步:
                // 1、将焦点设置到TextBox控件上
                textBox1.Focus();
                // 2、将文本框的起始点设置到最后
                textBox1.SelectionStart = textBox1.TextLength; 
                // 3、将控件内容滚动到当前插入位置,当前插入位置由SelectionStart设置
                textBox1.ScrollToCaret(); 
            }
            else
            {
                MessageBox.Show("没有选择文件");
            }
        }
    }
}

</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值