Skip to content

Instantly share code, notes, and snippets.

@pocheptsov
Created October 8, 2015 14:14
Show Gist options
  • Select an option

  • Save pocheptsov/7211f9cac1210d6407db to your computer and use it in GitHub Desktop.

Select an option

Save pocheptsov/7211f9cac1210d6407db to your computer and use it in GitHub Desktop.
Rename files in current folder based on modification date
using System;
using System.IO;
namespace rename
{
class Program
{
static void Main(string[] args)
{
var subfolderName = args?.Length > 0 ? args[0] : Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
int ind;
var fileInfos = new DirectoryInfo(subfolderName).GetFiles("*", SearchOption.AllDirectories);
for (ind = 0;ind < fileInfos.Length;ind++)
{
var fileInfo = fileInfos[ind];
if (string.CompareOrdinal(fileInfo.Extension, ".exe") == 0)
{
continue;
}
var destFileName = Path.Combine(fileInfo.DirectoryName, fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH-mm") + fileInfo.Extension);
MoveOrRename(fileInfo.FullName, destFileName);
Console.WriteLine($@"Renamed {fileInfo.FullName} - {destFileName}");
}
Console.WriteLine($@"Files processed {ind}");
Console.ReadLine();
}
public static bool EqualSize(string sourceFileName, string destFileName)
{
if (File.Exists(sourceFileName) && File.Exists(destFileName))
{
return new FileInfo(sourceFileName).Length == new FileInfo(destFileName).Length;
}
return false;
}
public static string MoveOrRename(string sourceFileName, string destFileName)
{
var fileName = Path.GetFileName(destFileName);
var fileExt = Path.GetExtension(fileName);
var folder = Path.GetDirectoryName(destFileName);
int ind;
bool skipMove = false;
for (ind = 1; File.Exists(destFileName) && !(skipMove = EqualSize(sourceFileName, destFileName)); ind++)
{
destFileName = Path.Combine(folder, $@"{fileName}_{ind}{fileExt}");
}
if (!skipMove)
{
File.Move(sourceFileName, destFileName);
}
return destFileName;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment