C# File Rename

[1 minute read]

I don’t have a direct need for this little class anymore, but I hate to delete it. Seems like something that would come in handy at some point in the future.

public static void Rename(string filePath, string newName)
    if (!File.Exists(filePath))
        throw new ArgumentException("A valid file path is required.", "filePath");

    if (string.IsNullOrWhiteSpace(newName))
        throw new ArgumentNullException("newName", "New name cannot be null or empty.");

    if (!Path.HasExtension(newName))
        throw new ArgumentException("New name must contain file extension.", "newName");

    if (newName.ToCharArray().Any(Path.GetInvalidFileNameChars().Contains))
        throw new ArgumentException("New name contains illegal filename characters.", "newName");

    newName = Path.Combine(new FileInfo(filePath).DirectoryName, newName);

    // This is the only .net method available to rename a file
    File.Move(filePath, newName);