I have a code that reads a lot of files in a loop from one location on disk and copy each file to another location. for each file copied, it also inserts a record (that contains the filename and other info) in a CopiedFiles table in a sqlserver db (using Entity Framework). The destination path must include a folder whose name include the id of the inserted CopiedFile (assigned by SqlServer at the moment of inserting), so I have to first insert into db, then copy the file in disk.
I have the File.Copy() inside a try/catch block, so if there is any problem when copying the file, it will just continue with next file. Of course, this creates a problem: in some cases, the input file can not be copied (for example corrupted file that throws an cyclic redundancy error when trying to copy it). In these cases, the db record has been inserted in the db but the file wont exist in the destination path in disk.
A simple solution would be to just delete the inserted record in db when the exception is thrown. But I would like to keep this code so that it only does inserts in db and not deletes...
So I was thinking another solution could be, before inserting the row in db, checking the file to make sure I will be able to copy it without errors. Now I am thinking possible ways to check this...
- one would be to actually copy the file to a temporary location, then if this goes ok, delete it from this temporary location, then saving row in db, then copy original file to destination. But of course, this would make the process twice as long (and the files to be copied are usually a lot, several thousands).
Could there be any other (more efficient) ways to check this?