在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例常用C#方法 → C#【文件夹】和【文件】的重命名

C#【文件夹】和【文件】的重命名

常用C#方法

下载此实例
  • 开发语言:C#
  • 实例大小:0.90M
  • 下载次数:37
  • 浏览次数:543
  • 发布时间:2015-09-16
  • 实例类别:常用C#方法
  • 发 布 人:夺标
  • 文件格式:.rar
  • 所需积分:5
 相关标签: 文件

实例介绍

【实例简介】

【所有子目录】:将左侧选择的目录 的所有子目录添加到右侧的ListView里

【所有子目录】:将左侧选择的目录及子目录的所有文件添加到右侧的ListView里

【添加到处理】:将左侧选择的目录里的文件添加到右侧ListView里

【实例截图】

【核心代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using ShellDll;
using System.IO;
using FileBrowser;

namespace FileReName
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        }
        private Config config;
        private void myfileBrowser_ContextMenuMouseHover(object sender, ContextMenuMouseHoverEventArgs e)
        {
            helpInfoLabel.Text = e.ContextMenuItemInfo;
        }

        private void myfileBrowser_SelectedFolderChanged(object sender, SelectedFolderChangedEventArgs e)
        {
            Icon icon = ShellImageList.GetIcon(e.Node.ImageIndex, true);

            if (icon != null)
            {
                currentDirInfo.Image = icon.ToBitmap();
                this.Icon = icon;
            }
            else
            {
                currentDirInfo.Image = null;
                this.Icon = null;
            }

            currentDirInfo.Text = e.Node.Text;
            this.Text = e.Node.Text;


        }

        private void tspbtnFolders_CheckedChanged(object sender, EventArgs e)
        {
            dualPane.Panel1Collapsed = !dualPane.Panel1Collapsed;
        }

        private void tspbtnOpenDir_Click(object sender, EventArgs e)
        {
            try
            {
                //判断最后一行数据是否是已经处理的文件    
                int nCount = fileView.Items.Count;
                if (nCount > 1)
                {
                    if (fileView.Items[nCount - 1].SubItems[0].Text.Substring(0, 3) == "总耗时")
                    {
                        tspbtnClearAll_Click(null, null);
                    }
                }              
                using (FolderBrowserDialog folderdlg = new FolderBrowserDialog())
                {
                    // Set the help text description for the FolderBrowserDialog.
                    folderdlg.Description = "选择需要处理的文件夹";
                    // Do not allow the user to create new files via the FolderBrowserDialog.
                    folderdlg.ShowNewFolderButton = false;
                    // Default to the My Documents folder.
                    folderdlg.RootFolder = Environment.SpecialFolder.Desktop;
                    // Show the FolderBrowserDialog.
                    DialogResult result = folderdlg.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        string strfolderName = folderdlg.SelectedPath;
                        DirectoryInfo di = new DirectoryInfo(strfolderName);
                        FileInfo[] filelist = di.GetFiles("*.*");
                        foreach (FileInfo fi in filelist)
                        {
                            this.fileView.Items.Add(fi.FullName);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }

        private void tspbtnOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                //判断最后一行数据是否是已经处理的文件    
                int nCount=fileView.Items.Count;
                if (nCount > 1)
                {
                    if (fileView.Items[nCount - 1].SubItems[0].Text.Substring(0, 3) == "总耗时")
                    {
                        tspbtnClearAll_Click(null, null);
                    }
                }               

                using (OpenFileDialog openFiledDialog = new OpenFileDialog())
                {

                    openFiledDialog.Multiselect = true;
                    openFiledDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    openFiledDialog.Filter = "图片文件(*.bmp;*.gif;*.jpg;*.png)|*.BMP;*.GIF;*.JPG;*.PNG|文本文件(*.txt)|*.txt|压缩文件(*.rar;*.zip)|*.rar;*.zip|所有文件(*.*)|*.*";
                    openFiledDialog.FilterIndex = 1;
                    if (openFiledDialog.ShowDialog() == DialogResult.OK)
                    {
                        foreach (string file in openFiledDialog.FileNames)
                        {
                            string fileName = System.IO.Path.GetFullPath(file);
                            ListViewItem item = new ListViewItem(new string[] { fileName });
                            fileView.Items.Add(item);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }

        private void tspbtnSetID_Click(object sender, EventArgs e)
        {
            frmSetId frm = new frmSetId();
            frm.ShowDialog();
        }

        private void tspbtnOK_Click(object sender, EventArgs e)
        {
            try
            {
                int nCount = fileView.Items.Count;
                if (nCount < 1)
                {
                    MessageBox.Show("请选择要处理的文件!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                config = new Config();
                config.cfgFile = Utility.ProstrConfigName;

                string strHeader="";
                string strLength = "";
                string strFooter = "";
                string strBegin = "";

                bool bIsDefault =false;//默认处理方式
                if (config.GetValue("//appSettings//add[@key='Default']") == "1")
                {
                    bIsDefault = true;
                    strLength = config.GetValue("//appSettings//add[@key='Length']");
                    strBegin = "1";
                }            
                else
                {
                    //获取重命名规则:CCAV-1-NB
                    strHeader = Utility.ProstrHeader;//前缀:如 CCAV-
                    strLength = Utility.ProstrLength;//序数增长步长 # 代表一位数
                    strFooter = Utility.ProstrFooter;//后缀(非后缀名,仅仅后缀修饰如 -NB)
                    strBegin = Utility.ProstrBegin;//开始序数,比如从 1 开始递增
                }

                if (strHeader == "" && strLength == "" && strFooter == "" && strBegin == "")
                {
                    //如未设置规则提示设置
                    frmSetId frm = new frmSetId();
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        strHeader = Utility.ProstrHeader;
                        strLength = Utility.ProstrLength;
                        strFooter = Utility.ProstrFooter;
                        strBegin = Utility.ProstrBegin;
                    }
                    else
                    {
                        return;
                    }
                }              
                                               
                int TotalFiles = 0;//获取处理文件个数
                DateTime StartTime = DateTime.Now;//获取开始时间           
                //获取步长/和步长序数
                int nXushu = Convert.ToInt32(strBegin);

                for (int i = 0; i < nCount; i  )
                {
                    //获取Listview中的文件
                    string strfile = fileView.Items[i].SubItems[0].Text;

                    if (strfile != "" && System.IO.File.Exists(strfile))
                    {//检验是否是文件路径格式

                        string strDirName = System.IO.Path.GetDirectoryName(strfile);

                        strBegin = nXushu.ToString().PadLeft(strLength.Length, '0');//针对二位数步长
                       
                        if (bIsDefault)//默认处理
                        {
                            strHeader = strDirName.Substring(strDirName.LastIndexOf('\\')   1)   "_";//如果是默认处理则获取文件夹名称
                        }                        

                        string strFileNameFormat = strHeader   strBegin   strFooter;

                        string strFilePath;//设置文件保存路径

                        string strDirectory = config.GetValue("//appSettings//add[@key='Directory']");//设置保存路径

                        if (strDirectory=="0")
                        {
                            strFilePath = strDirName;// strfile.Substring(0, strfile.LastIndexOf('\\'));//原始路径
                        }
                        else if (strDirectory=="-1")
                        {//创建子目录
                            
                            strFilePath = strfile.Substring(0, strfile.LastIndexOf('\\'))  "\\"  strDirName.Substring(strDirName.LastIndexOf('\\')   1);//路径

                            if (!Directory.Exists(strFilePath))
                            {
                                DirectoryInfo DirInfo = Directory.CreateDirectory(strFilePath);//用于创建指定目录的文件夹
                            }
                        }
                        else
                        {//指定路径
                            strFilePath = strDirectory;
                        }

                        string strFileName = strfile.Substring(strfile.LastIndexOf('\\')   1);//文件名
                        string strFileExt = strFileName.Substring(strFileName.LastIndexOf('.'));//文件后缀
                        string strNewFile = strFilePath   "\\"   strFileNameFormat   strFileExt;//新文件名

                        if (strDirectory == "0")
                        {
                            File.Move(strfile, strNewFile);//改文件名
                        }
                        else
                        {
                            File.WriteAllBytes(strNewFile, File.ReadAllBytes(strfile));//复制
                        }
                        fileView.Items[i].SubItems[0].Text = strNewFile;
                        nXushu  = 1;
                        TotalFiles  = 1;
                    }
                }

                //重新加载该目录到ListView
                DateTime EndTime = DateTime.Now;//获取结束时间
                TimeSpan ts = EndTime - StartTime;
                this.fileView.Items.Add("总耗时:"   ts.Hours.ToString()   "时"   ts.Minutes.ToString()   "分"   ts.Seconds.ToString()   "秒;"   "共处理:"   TotalFiles.ToString()   "个文件…");
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }

        }

        private void tspbtnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void tspbtnAllDir_Click(object sender, EventArgs e)
        {
           String[] dirs = Directory.GetDirectories(@"C:\");
           //fileView.Items.AddRange(
        }

        private void tspbtnAllFile_Click(object sender, EventArgs e)
        {

        }

        private void tspbtnAdd_Click(object sender, EventArgs e)
        {

        }

        private void tspbtnClearCheck_Click(object sender, EventArgs e)
        {
            int nmaxselect = fileView.SelectedItems.Count;
            for (int i = 0; i < nmaxselect; nmaxselect--)
            {
                fileView.Items.RemoveAt(fileView.SelectedItems[0].Index);
            }
        }

        private void tspbtnClearAll_Click(object sender, EventArgs e)
        {
            fileView.Items.Clear();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            int nWidth = fileView.Width;
            fileView.FullRowSelect = true;
            fileView.View = View.Details;
            fileView.Columns.Add("文件", nWidth);
        }

        private void fileView_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int nSelectFile = fileView.SelectedItems.Count;
                for (int i = 0; i < nSelectFile; nSelectFile--)
                {
                    string strfile = fileView.SelectedItems[0].Text;
                    if (strfile != "" && System.IO.File.Exists(strfile))
                    {
                        System.Diagnostics.Process.Start(strfile);
                    }
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }
    }
}

标签: 文件

实例下载地址

C#【文件夹】和【文件】的重命名

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警