使用OpenFileDialog對話框打開文本文件
using System;using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace test
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void 打開ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "打開(Open)";
ofd.FileName = "";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//為了獲取特定的係統文件夾,可以使用System.Environment類的靜態方法GetFolderPath()。該方法接受一個Environment.SpecialFolder枚舉,其中可以定義要返回路徑的哪個係統目錄
ofd.Filter = "文本文件(*.txt)|*.txt";
ofd.ValidateNames = true; //文件有效性驗證ValidateNames,驗證用戶輸入是否是一個有效的Windows文件名
ofd.CheckFileExists = true; //驗證路徑有效性
ofd.CheckPathExists = true; //驗證文件有效性
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(ofd.FileName, System.Text.Encoding.Default);
this.richTextBox1.Text = sr.ReadToEnd();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
}
最後更新:2017-04-02 00:06:40