您的位置:首页 > 编程语言 > C#

C#打开文件对话框

2014-03-19 17:34 429 查看
  这是我写的第一个C#程序,拆分百科词条用的.词条包一般至少在10W左右,多的也有50W+的,但每次任务只能导入5K,之前一直手动拆分的,费时费力,而且我耐心不足,分着分着就干别的去了.所以分出来的质量也不高.

  


  界面如上图.点击浏览,会弹出打开文件对话框.如下图

  


  代码如下

private void button2_Click(object sender, EventArgs e)
{
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.openFileDialog1.FileName = "打开文件";
this.openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
this.openFileDialog1.FilterIndex = 2;
this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOk);

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filename = openFileDialog1.FileName;
textBox2.Text = filename;

}

}


  代码说明:

  *button2就是"浏览"按钮,被点击后触发函数;

  *新建一个System.Windows.Forms.OpenFileDialog()对象,即打开文件对话框;

  *FileName这个成员就是文件名后面出现的text框里的内容.(我这里用法不对).可以用它得到所选文件的文件名,我应该设置一个默认的文件名或者置空;

  *FileOk当用户单击文件对话框中的“打开”或“保存”按钮时发生;


*Filter获取或设置当前文件名筛选器字符串,"该字符串决定对话框的“另存为文件类型”或“文件类型”框中出现的选择内容。"


  *Fliter的格式是"文件说明|文件后缀",如"txt files (*.txt)|*.txt",如果有多个筛选的话,也用"|"隔开,如"txt files (*.txt)|*.txt|All files (*.*)|*.*";(*是通配符)

  *FilterIndex是索引,通俗的说就是默认显示的筛选选项,我设置为"2",所以默认显示"All files (*.*)";

  *openFileDialog1.ShowDialog() "打开文件"对话框就出现;

      *其返回值为DialogResult.OK(确定)或DialogResult.Cancel(取消);

      *如果点击"确定",则执行把openFileDialog1.FileName赋值给filename,然后filename作为打开文件的参数,打开指定文件;


*CommonDialog.ShowDialog 方法

    *此方法实现 RunDialog

    *如果用户在对话框中单击“确定”,则为 DialogResult.OK;否则为 DialogResult.Cancel


  *textBox2.Text = filename;"浏览"前面的textbox为textBox2,把文件名显示在这里,是为了用户方便;

下面是MSDN的OpenFileDialog内容,我先摘一些有用的,不要怪我懒......

先上代码吧:

private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();

openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;

if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}


  我的代码差不多跟人家的相同(汗)

  *InitialDirectory,是初始的文件目录;


  *RestoreDirectory的值为true or false;表示是否储存上次选择的目录;

  *MSDN英文原文:true if the dialog box restores the current directory to its original value if the user changed the directory while searching for files; otherwise, false. /*汉语翻译貌似有问题. 但是我试验了几次都不知道这个怎么用,我用true或者false结果都相同(汗)*/


  成员


$ AddExtension

  *获取或设置一个值,该值指示如果用户省略扩展名,对话框是否自动在文件名中添加扩展名。

$CheckFileExists

  *如果对话框在用户指定的文件名不存在时显示警告,则为 true;反之,则为 false。 默认值为 true。

$Multiselect

  *获取或设置一个值,该值指示对话框是否允许选择多个文件。

$SafeFileName

  *获取对话框中所选文件的文件名和扩展名。 文件名不包含路径。

  *如:filename=openFileDialog1.SafeFileName;则filename的值只是文件名,没有路径;



---恢复内容结束---
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: