首页 > 代码库 > 操作文件

操作文件

将指定文件夹中的文件大小、文件名称以及最后修改时间,并将记录到Excel中。

private delegate void UpdateControlPropertyDelegate(Control ctrl, string propertyName, params object[] args);
private UpdateControlPropertyDelegate _updateCtrlPropDelegate = null;
private DirectoryInfo _workingDirectoryInfo = null;
private string _searchFilePattern = "*.*";
public FrmExportMain()
{
    InitializeComponent();
    this._updateCtrlPropDelegate = new UpdateControlPropertyDelegate(UpdateControlPropertyMethod);
}
private void UpdateControlPropertyMethod(Control ctrl, string propertyName, params object[] args)
{
    if (String.IsNullOrEmpty(propertyName))
    {
        ctrl.Update();
        return;
    }


    if (args == null)return;

    PropertyInfo[] props = ctrl.GetType().GetProperties();
    foreach (PropertyInfo propInfo in props)
    {
        //查找目标控件的属性名称
        if (propInfo.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase))
            propInfo.SetValue(ctrl, args[0], null);
    }
    ctrl.Update();
}

 

/// <summary>
/// 提取文件信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetFileInfo_Click(object sender, EventArgs e)
{
    if (System.IO.Directory.Exists(this.txtDirectoryName.Text) == false)
    {
    MessageBox.Show("当前选择的文件夹不存在,请重新选择!");
    return;
    }
    this._workingDirectoryInfo = new DirectoryInfo(this.txtDirectoryName.Text);
    this._searchFilePattern = this.txtSearchPattern.Text;
    this.btnGetFileInfo.Enabled = false;
    this.lblHint.Text = "";
    this.lblHint.Visible = true;
    BackgroundWorker backWorkderGetFileInfo = new System.ComponentModel.BackgroundWorker();
    backWorkderGetFileInfo.DoWork += new DoWorkEventHandler(backWorkderGetFileInfo_DoWork);
    backWorkderGetFileInfo.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backWorkderGetFileInfo_RunWorkerCompleted);
    backWorkderGetFileInfo.RunWorkerAsync();
}


private void InvokeUpdateControlProperty(Control ctrl, string propertyName, params object[] args)
{
    ctrl.Invoke(this._updateCtrlPropDelegate, new object[] { ctrl, propertyName, args });
}


private List GetDirectoryFileInfos(DirectoryInfo dirInfo)
{
    if (dirInfo == null)return null;

    List fileInfoList = new List();
    DirectoryInfo[] subDirs = dirInfo.GetDirectories();
    if (subDirs.Length > 0)
    {
        foreach (DirectoryInfo subDirInfo in subDirs)
        {
            InvokeUpdateControlProperty(this.lblHint, "Text", "正在获取文件夹【" + subDirInfo.Name + "】下文件信息,请稍等......");
            fileInfoList.AddRange(GetDirectoryFileInfos(subDirInfo));
            System.Threading.Thread.Sleep(1);//此句是重中之重,最关键的一句,降低了CPU的性能
        }
    }
    fileInfoList.AddRange(dirInfo.GetFiles(this._searchFilePattern));
    return fileInfoList;
}


public string ExcelReportFolderName
{
    get
    {
        string currentAppPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        string excelPath = Path.Combine(currentAppPath, "Reports");
        if (Directory.Exists(excelPath) == false)
        {
            Directory.CreateDirectory(excelPath);
        }
        return excelPath;
    }
}


private void backWorkderGetFileInfo_DoWork(object sender, DoWorkEventArgs e)
{
    List fileInfoList = GetDirectoryFileInfos(this._workingDirectoryInfo);
    InvokeUpdateControlProperty(this.lblHint, "Text", "正在生成Excel文件信息,请稍等......");
    StringBuilder sb = new StringBuilder();
    int index = 1;
    sb.Append("<html><body><table><tr><td>序号</td><td>文件名</td><td>文件大小</td><td>最后修改时间</td></tr>");

    foreach (FileInfo fileInfo in fileInfoList)
    {
        sb.Append("<tr><td>" + index + "</td><td>" + fileInfo.Name + "</td><td>" + fileInfo.Length + "</td><td>" + fileInfo.LastWriteTime + "</td></tr>");
        index++;
    }
    sb.Append("");

    string excelPath = ExcelReportFolderName;
    string excelFileName = Path.Combine(excelPath, DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
    StreamWriter logWriter = File.CreateText(excelFileName);
    try
    {
        logWriter.WriteLine(sb.ToString());
    }
    finally
    {
        logWriter.Close();
    }
}


private void backWorkderGetFileInfo_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    this.lblHint.Visible = false;
    if (e.Error != null)
        MessageBox.Show(e.Error.Message);
    else
        MessageBox.Show("获取文件信息成功!");
    this.btnGetFileInfo.Enabled = true;
}


/// <summary>
/// 选择文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelectDirectory_Click(object sender, EventArgs e)
{
    this.folderBrowserDialog1.SelectedPath = this.txtDirectoryName.Text;
    if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
    {
        this.txtDirectoryName.Text = this.folderBrowserDialog1.SelectedPath;
    }
}
/// <summary>
/// 打开报告文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOpenReportFolder_Click(object sender, EventArgs e)
{
    string filePath = ExcelReportFolderName;
    Process open = new Process();
    open.StartInfo.FileName = "explorer";
    open.StartInfo.Arguments = filePath;
    open.Start();
}

源码下载:http://files.cnblogs.com/alixee/ExportFileInfo%28%E4%BC%98%E5%8C%96%E5%90%8E%29.zip

操作文件