Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,13 @@ public static void ExecuteRenameFileWithFileClass()

Directory.Delete(directoryPath, true);
}
}

public static string ChangeExtension(string filePath, string newExtension)
{
var newFilePath = Path.ChangeExtension(filePath, newExtension);

File.Move(filePath, newFilePath);

return newFilePath;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace RenameFilesWithCSharp;

public static class FolderRenameService
{
public static void RenameFolder(string oldFolder, string newFolder)
{
Directory.Move(oldFolder, newFolder);
}

public static void ExecuteRenameFolder()
{
var parentPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

var oldFolder = Path.Combine(parentPath, "Invoices2025");
Directory.CreateDirectory(Path.Combine(oldFolder, "Q1"));
File.Create(Path.Combine(oldFolder, "Q1", "invoice-001.pdf")).Dispose();

var newFolder = Path.Combine(parentPath, "Invoices-2025");

RenameFolder(oldFolder, newFolder);

Console.WriteLine($"Renamed {Path.GetFileName(oldFolder)} to {Path.GetFileName(newFolder)}");
Console.WriteLine($"Invoice moved along: {File.Exists(Path.Combine(newFolder, "Q1", "invoice-001.pdf"))}");

Directory.Delete(parentPath, true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,45 @@ public static void RenameImagesWithDateTime(string directoryPath)

var fileExtension = Path.GetExtension(imageFile);

var newFileName = $"Image_{creationTime:yyyy-MM-dd_HHmmss}{fileExtension}";
var baseName = $"Image_{creationTime:yyyy-MM-dd_HHmmss}";

var newFilePath = Path.Combine(directoryPath, newFileName);
var newFilePath = Path.Combine(directoryPath, $"{baseName}{fileExtension}");

for (var copy = 1; File.Exists(newFilePath) && newFilePath != imageFile; copy++)
{
newFilePath = Path.Combine(directoryPath, $"{baseName}_{copy}{fileExtension}");
}

File.Move(imageFile, newFilePath);
}
}
}

public static void RenameImagesWithDateTimeUsingFileInfo(string directoryPath)
{
var allowedExtensions = new[] { ".jpg", ".png", ".jpeg", ".gif" };

var imageFiles = Directory.EnumerateFiles(directoryPath)
.Where(file => allowedExtensions.Contains(Path.GetExtension(file),
StringComparer.OrdinalIgnoreCase));

foreach (var imageFile in imageFiles)
{
var file = new FileInfo(imageFile);

var creationTime = file.CreationTime;

var fileExtension = file.Extension;

var baseName = $"Image_{creationTime:yyyy-MM-dd_HHmmss}";

var newFilePath = Path.Combine(directoryPath, $"{baseName}{fileExtension}");

for (var copy = 1; File.Exists(newFilePath) && newFilePath != imageFile; copy++)
{
newFilePath = Path.Combine(directoryPath, $"{baseName}_{copy}{fileExtension}");
}

file.MoveTo(newFilePath);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
using RenameFilesWithCSharp;

FileFinderService.ExecuteFindFilesInFolder();
FileRenameService.ExecuteRenameFileWithFileClass();
FileInfoRenameService.ExecuteRenameFileWithFileInfoClass();
FolderRenameService.ExecuteRenameFolder();
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net8.0</TargetFramework>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
</Project>
86 changes: 85 additions & 1 deletion files-csharp/RenameFilesWithCSharp/Tests/RenameFilesUnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,88 @@ public void WhenBatchRenamingPhotosWithDateTimeAndNoAllowedExtensionsExist_ThenN
// Assert
Assert.Equal(existingFiles, updatedFiles);
}
}

[Fact]
public void WhenTwoPhotosShareACreationSecond_ThenBothAreRenamedWithoutCollision()
{
var first = Path.Combine(_tempDirectory, "a.jpg");
var second = Path.Combine(_tempDirectory, "b.jpg");
File.Create(first).Close();
File.Create(second).Close();
var sameSecond = new DateTime(2025, 6, 1, 10, 30, 0);
File.SetCreationTime(first, sameSecond);
File.SetCreationTime(second, sameSecond);

// Act
ImageRenameService.RenameImagesWithDateTime(_tempDirectory);

// Assert
var names = Directory.GetFiles(_tempDirectory).Select(f => Path.GetFileName(f)).Order(StringComparer.Ordinal).ToArray();
Assert.Equal(["Image_2025-06-01_103000.jpg", "Image_2025-06-01_103000_1.jpg"], names);
}

[Fact]
public void WhenBatchRenameRunsTwice_ThenSecondRunChangesNothing()
{
var sameSecond = new DateTime(2025, 6, 1, 10, 30, 0);
foreach (var name in new[] { "a.jpg", "b.jpg" })
{
var path = Path.Combine(_tempDirectory, name);
File.Create(path).Close();
File.SetCreationTime(path, sameSecond);
}
ImageRenameService.RenameImagesWithDateTimeUsingFileInfo(_tempDirectory);
var afterFirstRun = Directory.GetFiles(_tempDirectory).Order().ToArray();

// Act
ImageRenameService.RenameImagesWithDateTimeUsingFileInfo(_tempDirectory);

// Assert
Assert.Equal(afterFirstRun, Directory.GetFiles(_tempDirectory).Order().ToArray());
}

[Fact]
public void GivenExistingFolder_WhenRenamingFolder_ThenContentMovesWithIt()
{
var oldFolder = Path.Combine(_tempDirectory, "Invoices2025");
Directory.CreateDirectory(oldFolder);
File.WriteAllText(Path.Combine(oldFolder, "invoice-001.pdf"), "content");
var newFolder = Path.Combine(_tempDirectory, "Invoices-2025");

// Act
FolderRenameService.RenameFolder(oldFolder, newFolder);

// Assert
Assert.False(Directory.Exists(oldFolder));
Assert.True(File.Exists(Path.Combine(newFolder, "invoice-001.pdf")));
}

[Fact]
public void GivenTextFile_WhenChangingExtension_ThenOnlyExtensionChanges()
{
var filePath = Path.Combine(_tempDirectory, "notes.txt");
File.WriteAllText(filePath, "content");

// Act
var newFilePath = FileRenameService.ChangeExtension(filePath, ".md");

// Assert
Assert.Equal(Path.Combine(_tempDirectory, "notes.md"), newFilePath);
Assert.True(File.Exists(newFilePath));
Assert.False(File.Exists(filePath));
}

[Fact]
public void GivenExistingDestination_WhenMovingWithoutOverwrite_ThenIOException()
{
var source = Path.Combine(_tempDirectory, "a.txt");
var destination = Path.Combine(_tempDirectory, "b.txt");
File.WriteAllText(source, "new");
File.WriteAllText(destination, "old");

Assert.Throws<IOException>(() => File.Move(source, destination));

File.Move(source, destination, overwrite: true);
Assert.Equal("new", File.ReadAllText(destination));
}
}
12 changes: 6 additions & 6 deletions files-csharp/RenameFilesWithCSharp/Tests/Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.2.0">
<PackageReference Include="coverlet.collector" Version="10.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RenameFilesWithCSharp\RenameFilesWithCSharp.csproj" />
</ItemGroup>
</Project>
</Project>
Loading