【发布时间】:2018-03-13 15:23:44
【问题描述】:
我有 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
}
}
}
}
【问题讨论】:
-
查看
System.IO.Path提供的方法,可以帮助您反汇编和组合路径字符串。还可以查看正则表达式 (System.Text.RegularExpressions.Regex),它肯定可以帮助您定义字符串替换/重命名的模式和规则。 -
您需要提出现有代码的问题,而不是要求读者为您编写代码。
//Need Code需要替换为您为尝试解决问题而编写的代码。 -
@elgonzo 在这种情况下,每个文件夹名称上的字符串替换函数可能比挖掘正则表达式更容易,因为 Harry 只想用
M替换Mode。虽然学习正则表达式总是好的。 -
@NOhs,是的,如果 Harry 只想替换一定数量的特定子字符串/单词,那么 string.Replace 确实要简单得多。 :-)
-
只有您确切地知道目录结构,才能决定使用的最佳策略。我们不知道是否还有其他文件夹,以及我们在检查文件名时必须有多严格...如果您直接控制的结构或结构可以包含用户文件...
标签: c# structure filenames directory