C# OpenFileDialog

OpenFileDialog 用于浏览并打开文件,在Windows Forms中使用,表现为标准的Windows对话框。

实例:

1.新建Windows Form Application

image

2.添加OpenFileDialog

打开Toolbox,找到并双击OpenFileDialog:

image

可以在窗口下方看到添加到OpenFileDialog.

3.添加按钮和事件

OpenFileDialog对话框需要通过事件激活,添加一个Button到Form中,双击Button以添加事件,事件代码如下:

using System;
using System.Windows.Forms;

namespace OpenFileDialog {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            // show the dialog and get result
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
            }
            Console.WriteLine(result);
        }
    }
}

4.读取文件

可以通过OpenFileDialog读取文件,修改按钮的点击事件,具体代码如下:

using System;
using System.IO;
using System.Windows.Forms;

namespace OpenFileDialog {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int size = -1;
            // show the dialog and get result
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                string file = openFileDialog1.FileName;
                try
                {
                    string text = File.ReadAllText(file);
                    size = text.Length;
                }
                catch (Exception)
                {
                    throw;
                }
            }
            Console.WriteLine(result);
            Console.WriteLine(size);    // 文件大小
        }
    }
}

编译运行,点击button1,会显示OpenFileDialog,然后验证DialogResult,通过File.ReadAllText读写文件,然后获得文件大小。

5. 属性

属性 说明
AddExtension 扩展名是否添加到文件名,默认为真,如果想自动修改文件扩展名,可将其设置为false。
AutoUpgradeEnabled 用于获得Vista风格的打开文件对话框,默认为true,推荐使用。
DefaultExt 默认文件扩展名,如果文件扩展名没有指定,则自动添加该扩展
DereferenceLinks 从对话框返回路径前是否解引用快捷键
FileName 在对话框最开始显式的文件名
InitialDirectory 对话框的初始目录
Multiselect 是否一次可选择多个文件,可通过SHIFT或CTRL键进行多项选择

6.Filter

Filters能帮助有效的筛选文件,OpenFileDialog支持文件名过滤,可用*代表任意字符。

Filter:

用于指定过滤器,如:“C# files|*.cs”,此时只显式以”.cs”结尾的文件

FilterIndex:

用于指定默认Filter,其Index为1.其后的filter的Index依次递增

ValidateNames:

Windows文件系统不允许文件名包含特定字符如”*”,该选项一般为True。

7.ReadOnly

OpenFileDialog部分属性可允许指定文件是否为只读。可以显式read-only checkbox。大多时候用不着.

ReadOnlyChecked:

用于设置”read only”复选框的值,仅当”ShowReadOnly”设置为True才可见。

ShowReadOnly:

“Read-only”复选框是否可见。

原文地址:https://www.cnblogs.com/jiawei-whu/p/4332361.html