C# 文件并从 1 自动重命名
本文关键字:重命名 文件 | 更新日期: 2023-09-27 18:36:03
我用 c# 编写了这段代码,用于更改文件夹的位置以及该文件夹的所有子文件夹。我想在将其复制到目的地时更改所有文件夹的名称。 例如,我想将名称从 1 更改为 .... .我应该如何更改我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace Folder
{
class clssMoveFolder
{
string temppath;
public string StrtxtSource;
public string destDirName;
public void Directorycopy(string sourceDirName, string destDirName, bool cutSubDirs, string strExtension)
{
try
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName);
}
FileInfo[] files = dir.GetFiles();
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
//Get the file contents of the directory to copy.
for (int a = 0; a < files.Length; ++a)
{
// Create the path to the new copy of the file.
if (files[a].Extension == "."+strExtension )
{
temppath = Path.Combine(destDirName, files[a].Name);
files[a].MoveTo(temppath);
}
else if (files[a].Extension == strExtension)
{
temppath = Path.Combine(destDirName, files[a].Name);
files[a].MoveTo(temppath);
}
else if (strExtension == "AllFiles")
{
temppath = Path.Combine(destDirName, files[a].Name);
files[a].MoveTo(temppath);
}
else
files[a].Delete();
dir.Refresh();
}
FileInfo[] filesCheck = dir.GetFiles();
if (dirs.Length == 0 && filesCheck.Length == 0 && dir.Name != StrtxtSource)
{
dir.Delete();
}
// If copySubDirs is true, copy the subdirectories.
if (cutSubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Copy the subdirectories.
string temppath= Path.Combine(destDirName, subdir.Name);
Directorycopy(subdir.FullName, temppath,cutSubDirs,strExtension);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
}
如果您只想在复制文件后重命名文件,则可以直接将其复制到其他名称下。 例如,您可以b.txt
将原始a.txt
复制到目标目录,而不是复制a.txt
并将其重命名为b.txt
。
可以使用 File.Move
方法进行重命名。
File.Move("a.txt", "b.txt");
如果您希望即使其他人将文件复制到目录中(例如,通过使用Windows资源管理器或其他应用程序编写的文件)也能执行此操作,则可能需要仔细查看FileSystemWatcher
。您可以使用它来监视指定目录(可选地包括其子目录)中的更改并对这些更改做出反应。
...
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"D:'SomeTestDirectory";
watcher.Filter = "*.*";
watcher.NotifyFilter = NotifyFilters.FileName; // Trigger only on events associated with the filename
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true; // Starts the "watching"
...
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Do whatever you want here, e.g. rename the file.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}