C#基础学习之二 文件读取 denuvead

http://blog.csdn.net/denuvead/article/details/2302288

1.一个button 命名为 btok

2.一个textbox 命名为 tbInput

3.一个Listbox 命名为 lbResult

ok 我们分别为button和listbox建立事件来实现显示textbox中路径下文件和listbox中选中文件的部分属性

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace complete
{
    
public partial class Form1 : Form
    
{
        
string currentpath;

        
public Form1()
        
{
            InitializeComponent();
        }


        
private void btOK_Click(object sender, EventArgs e)
        
{
            
//从TextBox中提取输入的字符
            string path = tbInput.Text;
            
//检查路径名是否合法
            if (path.Length > 0)
            
{
                
if (Directory.Exists(path))
                
{
                    lbResult.Items.Clear();
                    
//获取目录中的所有文件名列表
                    string[] files = Directory.GetFiles(path);

                    
//将文件去掉路径名放在列表框中
                    foreach (string file in files)
                    
{
                        FileAttributes attr 
= File.GetAttributes(file);
                        
if ((attr & FileAttributes.Hidden) == 0)
                            lbResult.Items.Add(Path.GetFileName(file));
                    }


                    
//在读者双击一个文件名的情况下保存路径名
                    currentpath = Path.GetFullPath(tbInput.Text);
                }


                
//如果路径无效,则告知读者
                else
                    MessageBox.Show(path
+" is not a valid path","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }


        }


        
private void lbResult_DoubleClick(object sender, EventArgs e)
        
{
            
//根据读者双击的文件名创建一个完全限定的文件名
            string file = currentpath;
            
if (!file.EndsWith(":"&& !file.EndsWith("//"))
                file 
+= "/";
            file 
+= lbResult.SelectedItem.ToString();

            
//显示文件创建时间和最后一次修改的时间
            DateTime created = File.GetCreationTime(file);
            DateTime modified 
= File.GetLastWriteTime(file);

            
string msg = "创建时间:" + created.ToLongDateString() + " 于:" + created.ToLongTimeString() + " " + "修改:" + modified.ToLongDateString() + " 于:" + modified.ToLongTimeString();
            MessageBox.Show(msg, lbResult.SelectedItem.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章