<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>
C#学习笔记之打开文件对话框
最新推荐文章于 2024-04-10 07:21:46 发布