C# 如何重命名所有文件并使每个文件的编号保持相同?
代码如下:C# 如何重命名所有文件并使每个文件的编号保持相同?,c#,C#,代码如下: static private void RenameFiles() { images = Directory.GetFiles(sf, "*.gif"); for (x = 0; x < images.Length; x++) { counter = counter + 1; Console.WriteLine("Working on current file: " + images[x]); if (File.E
static private void RenameFiles() {
images = Directory.GetFiles(sf, "*.gif");
for (x = 0; x < images.Length; x++) {
counter = counter + 1;
Console.WriteLine("Working on current file: " + images[x]);
if (File.Exists(images[x])) {
NewImages = System.Drawing.Image.FromFile(images[x]);
NewImages.Save(sf + "\\" + "radar" + counter.ToString("D6") + ".Gif", System.Drawing.Imaging.ImageFormat.Gif);
NewImages.Dispose();
}
}
}
静态私有void重命名文件(){
images=Directory.GetFiles(sf,“*.gif”);
对于(x=0;x
例如,现在的第一个文件名是:radar\u temp\u directoryradar000002
最后一个文件名是:
radar\u temp\u directorydar008760
我想做的是,最后第一个文件名是:radar000002
下一个文件名将是:
radar000003
最后一个文件名为:
radar008760
要保留数字,只需将名称从radar\u temp\u directorydar
更改为radar
现在不应该更改格式,因为它们都是Gif格式,所以应该保持Gif格式 我现在的做法是创建新的文件,比如第一个文件:
radar000001
最后一个是:
radar008759
而且旧文件也保存了下来 我想重命名现有文件,而不是创建新文件。使用重命名文件
if (File.Exists(images[x]))
{
File.Move(images[x], "radar" + counter.ToString("D6") + ".gif");
}
要在新名称中获得相同的数字,请使用旧名称作为基数,而不是使用计数器:
static private void RenameFiles() {
images = Directory.GetFiles(sf, "*.gif");
foreach (string name in images) {
Console.WriteLine("Working on current file: " + name);
string newName = name.Replace("radar_temp_directory", String.Empty);
File.Move(name, newName);
}
}
上面的代码假设路径名中没有radar\u temp\u目录
,如果可能的话,您应该获取文件名并仅对以下内容进行替换:
string newName = Path.Combine(Path.GetFullPath(name), Path.GetFileName(name).Replace("radar_temp_directory", String.Empty));
重命名与文件系统中的移动操作相同。Guffa它通常工作,但newName的目录与变量:name不同。例如,现在的新名称是:C:\Users\bout0\u 000\AppData\Local\mws\My Weather Station\\radar00004.Gif,名称是:C:\Users\bout0\u 000\AppData\Local\mws\My Weather Station\radar\u temp\u directory\radar\u temp\u directoryRadar00004.Gif将RADAR00004放在C:\Users\bout0\u 000\AppData\Local\mws\My Weather Station中,而不是替换位于以下位置的旧文件:C:\Users\bout0\u 000\AppData\Local\mws\My气象站\radar\u temp_directory@user3596190:由于路径还包含
radar\u temp\u目录
,您需要使用另一种创建新名称的方法,即只更改文件名并保持路径不变。也许你在我把那部分加进去之前已经看过了。