using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;
using System.Management;
namespace test_code
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenamePngFiles(folderDlg.SelectedPath);
}
private void RenamePngFiles(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in System.IO.Directory.EnumerateFiles(directoryPath, "*.png", new EnumerationOptions()))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}
}
以上是我的代码,我不知道为什么我不能删除上述错误。我尝试了各种命名空间,但就是摆脱不了它。我使用的是。netframework 4.7.2。正如你所看到的,我所要做的就是重命名文件夹中的所有文件,包括子文件夹,并加上#和一个数字,该数字根据文件夹中的文件数量不断增加。
结合上面的注释,我做了以下修改:
更新:
修改选中路径中的所有png文件。
RenameAllPngFiles(folderDlg.SelectedPath);
以下是自定义函数:
重命名所有png文件:
private void RenameAllPngFiles(string directoryPath) {
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath)) {
RenameCurrentPng(item.FullName);
}
}
重命名当前目录下的所有png文件:
private void RenameCurrentPng(string directoryPath) {
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png")) {
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
获取所有子文件夹的地址:
private DirectoryInfo[] GetDirectoryInfos(string directoryPath) {
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
如果你对我的代码有疑问,请在下面评论,我会跟进的