Refactoring common file handling logic