C#编程实现对特定扩展名文件的检索

1.需求

  从网上下载了很多网页文件,里面有很多图片资源,想一下子提取出来,但是有些文件分布在不同的文件夹下而文件名是相同的,拷贝到同一个文件夹下会出现覆盖的情况,因此编写了这个程序,检索出图片资源,并按照一定格式对图片重新命名,这样就将所有图片资源一下子提取出来了,效率大大提高。

2.程序界面

3.程序代码

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

namespace SearchAndRename
{
    public partial class frmMain : Form
    {
        private int count = 1;
        private string serialNumber = "";
        private string newFileName = "";
        private string newFilePath = "";
        private const int WM_VSCROLL = 0x115;
        private const int SB_BOTTOM = 7;
        [DllImport("user32")]
        private extern static int SendMessage(int hWnd, int wMsg, int wParam, int lParam);

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            InitControls();
        }

        private void btnBrowse1_Click(object sender, EventArgs e)
        {
            FolderDialog openFolder = new FolderDialog();
            if (openFolder.DisplayDialog() == DialogResult.OK)
            {
                tbxSrcPath.Text = openFolder.Path.ToString();
            }
            else
            {
                tbxSrcPath.Text = "你没有选择目录";
            }
        }

        private void btnBrowse2_Click(object sender, EventArgs e)
        {
            FolderDialog openFolder = new FolderDialog();
            if (openFolder.DisplayDialog() == DialogResult.OK)
            {
                tbxDstPath.Text = openFolder.Path.ToString();
            }
            else
            {
                tbxDstPath.Text = "你没有选择目录";
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(tbxStartNumber.Text))
            {
                MessageBox.Show("Start Number is invalid.", "Error");
                return;
            }
            else
            {
                count = Int32.Parse(tbxStartNumber.Text);
            }
            if (Directory.Exists(tbxSrcPath.Text))
            {
                lvFiles.Items.Clear();
                tbxSrcPath.Enabled = false;
                btnBrowse1.Enabled = false;
                tbxDstPath.Enabled = false;
                btnBrowse2.Enabled = false;
                tbxPrefix.Enabled = false;
                tbxStartNumber.Enabled = false;
                tbxExt.Enabled = false;
                btnStart.Enabled = false;
                ListViewItem item = new ListViewItem();
                int sum = 0;
                string[] rootFiles = Directory.GetFiles(tbxSrcPath.Text);
                foreach (string rootfile in rootFiles)
                {
                    if (sum % 10 == 0) Application.DoEvents();
                    FileInfo fileInfo = new FileInfo(rootfile);
                    if (fileInfo.Name.Substring(fileInfo.Name.Length - 4, 4).ToUpper().Equals(tbxExt.Text.ToUpper()))
                    {
                        serialNumber = count.ToString();
                        newFileName = String.Format("{0}{1:D6}{2}", tbxPrefix.Text, count, tbxExt.Text);
                        newFilePath = String.Format("{0}\\{1}", tbxDstPath.Text, newFileName);
                        File.Copy(rootfile, newFilePath, true);
                        //item = lvFiles.Items.Add(fileInfo.Name);
                        item = lvFiles.Items.Add(serialNumber);
                        item.SubItems.AddRange(new string[] { rootfile, newFilePath, System.DateTime.Now.ToString("G") });
                        count++;
                        tbxStartNumber.Text = count.ToString();
                    }
                }
                SearchAllFiles(tbxSrcPath.Text);
                tbxSrcPath.Enabled = true;
                btnBrowse1.Enabled = true;
                tbxDstPath.Enabled = true;
                btnBrowse2.Enabled = true;
                tbxPrefix.Enabled = true;
                tbxStartNumber.Enabled = true;
                tbxExt.Enabled = true;
                btnStart.Enabled = true;
                SendMessage(lvFiles.Handle.ToInt32(), WM_VSCROLL, SB_BOTTOM, 0);
            }
            else
            {
                MessageBox.Show("请选择需要搜索的路径!!");
            }

        }
        /// <summary>
        /// 初始化控件
        /// </summary>
        private void InitControls()
        {
            tbxSrcPath.Text = @"F:\lod\temp";
            tbxDstPath.Text = @"F:\lod\wpjtemp";
            tbxPrefix.Text = "WPJK";
            tbxStartNumber.Text = "1";
            tbxExt.Text = ".JPG";
            lvFiles.View = View.Details;
            lvFiles.Columns.Add("SN", 50, HorizontalAlignment.Center);
            lvFiles.Columns.Add("Source File", 200, HorizontalAlignment.Center);
            lvFiles.Columns.Add("Dest File", 200, HorizontalAlignment.Center);
            lvFiles.Columns.Add("Found Time", 150, HorizontalAlignment.Center);
        }

        private void SearchAllFiles(string strPath)
        {
            ListViewItem item = new ListViewItem();
            int sum = 0;
            string[] folders = Directory.GetDirectories(strPath);
            foreach (string folder in folders)
            {
                if (sum % 10 == 0) Application.DoEvents();
                sum += 1;
                DirectoryInfo folderInfo = new DirectoryInfo(folder);
                //item = lvFiles.Items.Add(folderInfo.Name);
                //item.SubItems.AddRange(new string[] { folder, "0", "目录" });
                item = lvFiles.Items.Add("Folder");
                item.SubItems.AddRange(new string[] { folder, "", "" });
                string[] files = Directory.GetFiles(folder);
                foreach (string file in files)
                {
                    if (sum % 10 == 0) Application.DoEvents();
                    sum += 1;
                    FileInfo fileInfo = new FileInfo(file);
                    if (fileInfo.Name.Substring(fileInfo.Name.Length - 4, 4).ToUpper().Equals(tbxExt.Text.ToUpper()))
                    {
                        serialNumber = count.ToString();
                        newFileName = String.Format("{0}{1:D6}{2}", tbxPrefix.Text, count, tbxExt.Text);
                        newFilePath = String.Format("{0}\\{1}", tbxDstPath.Text, newFileName);
                        File.Copy(file, newFilePath, true);
                        //item = lvFiles.Items.Add(fileInfo.Name);
                        item = lvFiles.Items.Add(serialNumber);
                        item.SubItems.AddRange(new string[] { file, newFilePath, System.DateTime.Now.ToString("G") });
                        count++;
                        tbxStartNumber.Text = count.ToString();
                    }
                }
                SearchAllFiles(folder);
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = MessageBox.Show("Are you sure to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (DialogResult.Yes != dr)
            {
                e.Cancel = true;
            }
        }
    }
}

4.总结

  程序在WinXP+VS2010先测试通过。

posted on 2012-10-24 22:24  onedime  阅读(651)  评论(0编辑  收藏  举报