Check and close file or connection first