У меня есть такие папки, как C: \ Users \ XXX \ Desktop \ Test \ DUT3_Mode1A \ DUT3_Mode1B \ DUT3_Mode2.

Я просматриваю папку до Test. Мне нужно изменить, если имя содержит Mode1A, тогда я просто переименовываю его в M1A, как другое условие с именами. Например, у меня есть путь DUT3_Mode1A \ DUT3_Mode1B \ DUT3_Mode2, мне нужно переименовать DUT3_M1A \ DUT3_M1B \ DUT3_M2

См. ниже пример того, что мне нужно изменить структуру папок.

    M1A = Mode1A
    M1B = Mode1B
    M2 = Mode2
    M3 = Mode3
    M6 = Mode6
    Read = Read DTCs
    Clear = Clear DTCs
    EPB = EPB_APPL-REL
    PWRD = POWER_DOWN    


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;

namespace FolderStructure
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        string strpath = string.Empty;
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "Custom Description";

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string sSelectedPath = fbd.SelectedPath;
                textBox1.Text = sSelectedPath;
                strpath = sSelectedPath;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ChangeFileName(strpath);
        }
        public void ChangeFileName(string folderPath)
        {
            string strtemp = string.Empty;            
            ////string[] folders = folderPath.Split(System.IO.Directory.GetDirectories(folderPath, "*", System.IO.SearchOption.AllDirectories););
            string[] folders = System.IO.Directory.GetDirectories(folderPath, "*", System.IO.SearchOption.AllDirectories);
            DirectoryInfo info = new DirectoryInfo(folderPath);
            foreach (string path in folders)
            {
                //code needed              

            }
        }
    }
}
0
Harry 13 Мар 2018 в 18:23

2 ответа

Лучший ответ

Этот метод переименует все каталоги и подкаталоги в заданном пути, заменив строку 'from' на строку 'to':

public static void Replace(string path, string from, string to)
{
    string prefix = path;
    string[] folders = System.IO.Directory.GetDirectories(path, "*", System.IO.SearchOption.TopDirectoryOnly);
    foreach (string folder in folders)
    {
        // recursively rename all subfolders first
        Replace(folder, from, to);

        string newFolderName = prefix + folder.Substring(prefix.Length).Replace(from, to);

        if (newFolderName != folder)
            System.IO.Directory.Move(folder, newFolderName);
    }
}

Применение

    Replace(folderPath, "Mode", "M");

РЕДАКТИРОВАТЬ: Вы уверены, что хотите изменить уровень сложности на легкий?

private static Dictionary<string, string> replacements = new Dictionary<string, string>
{
    { "Mode1A", "M1A" },
    { "Mode1B", "M1B" },
    { "Mode1", "M1" },
    { "Mode2", "M2" },
    { "Mode3", "M3" },
    { "Mode6", "M6" },
    { "Read DTCs", "Read" },
    { "Clear DTCs", "Clear" },
    { "EPB_APPL-REL", "EPB" },
    { "POWER_DOWN", "PWRD" }
};

private void button2_Click(object sender, EventArgs e)
{
    ChangeFolderNames();
}

private void ChangeFolderNames()
{
    foreach(KeyValuePair<string, string> pair in replacements)
        Replace(strpath, pair.Key, pair.Value);
}

public static void Replace(string path, string from, string to)
{
    string prefix = path;
    string[] folders = System.IO.Directory.GetDirectories(path, "*", System.IO.SearchOption.TopDirectoryOnly);
    foreach (string folder in folders)
    {
        // recursively rename all subfolders first
        Replace(folder, from, to);

        string newFolderName = prefix + folder.Substring(prefix.Length).Replace(from, to);

        if (newFolderName != folder)
            System.IO.Directory.Move(folder, newFolderName);
    }
}
2
Steve Harris 15 Мар 2018 в 09:04

Вы можете изменить рекурсивный метод ниже, чтобы переименовать файлы. Приведенный ниже код записывает все имена файлов в формат xml.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace SAveDirectoriesXml
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string FOLDER = @"c:\temp";
        static XmlWriter writer = null;
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            writer = XmlWriter.Create(FILENAME, settings);
            writer.WriteStartDocument(true);

            DirectoryInfo info = new DirectoryInfo(FOLDER);
            WriteTree(info);

            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
            Console.WriteLine("Enter Return");
            Console.ReadLine();

        }
        static long WriteTree(DirectoryInfo info)
        {
            long size = 0;
            writer.WriteStartElement("Folder");
            try
            {
                writer.WriteAttributeString("name", info.Name);
                writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
                writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
                writer.WriteAttributeString("date", info.LastWriteTime.ToString());


                foreach (DirectoryInfo childInfo in info.GetDirectories())
                {
                    size += WriteTree(childInfo);
                }

            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            FileInfo[] fileInfo = null;
            try
            {
                fileInfo = info.GetFiles();
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error",errorMsg);
            }

            if (fileInfo != null)
            {
                foreach (FileInfo finfo in fileInfo)
                {
                    try
                    {
                        writer.WriteStartElement("File");
                        writer.WriteAttributeString("name", finfo.Name);
                        writer.WriteAttributeString("size", finfo.Length.ToString());
                        writer.WriteAttributeString("date", info.LastWriteTime.ToString());
                        writer.WriteEndElement();
                        size += finfo.Length;
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
                        Console.WriteLine(errorMsg);
                        writer.WriteElementString("Error", errorMsg);
                    }
                }
            }

            writer.WriteElementString("size", size.ToString());
            writer.WriteEndElement();
            return size;

        }
    }
}
0
jdweng 13 Мар 2018 в 15:29