Search code examples
c#guidfile-rename

c# Create a unique name with a GUID


I am creating a back up solution. I doubt there is anything new in what I'm trying to achieve.

Before copying the file I want to take a backup of the destination file in case anything becomes corrupt. This means renaming the file.

I have to be careful when renaming in case the file already exists and adding a 01 to the end is not safe.

My question is, based upon not finding the answer else where, would adding a GUID to the file name work. So, if my file was called file01.txt, renaming the file to file01.txtGUID (where GUID is the generated GUID), I could then perform my back up of that file (at this instance having 2 back ups) and then, after ensuring the file has copied (by comparing length of file to the source), delete the file with the GUID in the name.

I know the GUID is not 100% guaranteed to be unique but would this suffice?


Solution

  • Just get a GUID, then ask the destination OS if name+GUID exists. If it does, then pick a new GUID and try again. You are going to delete the name+GUID file anyway, so who cares if you can't pick a unique filename on the first try.

    I think you might be focusing on the wrong problems given the risk and impact.

    What if you don't have disk space to make two backups on the destination system?

    What if the filename + path is too long for the destination OS to handle?

    What is someone else modifies the file in the period of time between when you get the name and try to perform an operation of time on the file?

    Writing defensive code is about thinking about risks, but don't drive yourself crazy that you focus on less likely or nearly impossible scenarios.