在WebForm中提供了FileUpload控件来供我们选择本地文件,只要我们将该控件拖到页面上了,就已经有了选择本地文件的功能了。而在 WinForm中,并没有为我们提供集成该功能的控件,但为提供了OpenFileDialog类,我们可以利用该类来打开与选择本地文件。
OpenFileDialog类,提供了提示用户打开文件的功能,它有如下属性和方法:
属性:
CheckFileExists--设置对话框在用户指定的文件名不存在时是否显示警告
Multiselect--设置是否允许用户同时选择多个文件
ReadOnlyChecked--获取或设置一个值,该值指示是否选定只读复选框
SafeFileName--获取对话框中所选文件的文件名和扩展名。文件名不包含路径
SafeFileNames--获取对话框中所有选定文件的文件名和扩展名的数组。文件名不包含路径
ShowReadOnly--获取或设置一个值,该值指示对话框是否包含只读复选框
方法:
OpenFile()--返回用户所选定的只读文件的 System.IO.Stream
Reset()--将所有属性重新设置为其默认值
private void button10_Click(object sender, EventArgs e)
{
//初始化一个OpenFileDialog类
OpenFileDialog fileDialog = new OpenFileDialog();
//判断用户是否正确的选择了文件
if (fileDialog.ShowDialog() == DialogResult.OK)
{
//获取用户选择文件的后缀名
string extension = Path.GetExtension(fileDialog.FileName);
//声明允许的后缀名
string[] str = new string[] { ".gif", ".jpge", ".jpg" };
if (!((IList)str).Contains(extension))
{
MessageBox.Show("仅能上传gif,jpge,jpg格式的图片!");
}
else
{
//获取用户选择的文件,并判断文件大小不能超过20K,fileInfo.Length是以字节为单位的
FileInfo fileInfo = new FileInfo(fileDialog.FileName);
if (fileInfo.Length > 20480)
{
MessageBox.Show("上传的图片不能大于20K");
}
else
{
//在这里就可以写获取到正确文件后的代码了
}
}
}
}
如果我们要为弹出的选择框中过滤文件类型,可以设置OpenFileDialog的Filter属性。比如我们只允许用户选择.xls文件,可以作如下设置:
fileDialog.Filter = "(*.xls)|*.xls";
另一个实现:
private void btnFile_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Title = "请选择文件";
fileDialog.Filter = "所有文件(*.*)|*.*";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string file = fileDialog.FileName;
MessageBox.Show("已选择文件:" + file, "选择文件提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btnPath_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择文件路径";
if (dialog.ShowDialog() == DialogResult.OK)
{
string foldPath = dialog.SelectedPath;
MessageBox.Show("已选择文件夹:" + foldPath, "选择文件夹提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("Explorer.exe", "c:\\windows");
}
参考文章:http://www.cnblogs.com/wangyt223/p/3214246.html
http://www.cnblogs.com/hwd-cnblogs/archive/2013/01/28/2879963.html