I only noticed that rename uses MOVEFILE_REPLACE_EXISTING flag, which can't be used with directories. Are you sure remove fails too? If rename throws, remove is not called in your code.