How to Generate unique file names in C#

后端 未结 19 2445
生来不讨喜
生来不讨喜 2020-12-02 05:43

I have implemented an algorithm that will generate unique names for files that will save on hard drive. I\'m appending DateTime: Hours,Minutes,Second an

19条回答
  •  执笔经年
    2020-12-02 06:09

    You can have a unique file name automatically generated for you without any custom methods. Just use the following with the StorageFolder Class or the StorageFile Class. The key here is: CreationCollisionOption.GenerateUniqueName and NameCollisionOption.GenerateUniqueName

    To create a new file with a unique filename:

    var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myfile.txt", NameCollisionOption.GenerateUniqueName);
    

    To copy a file to a location with a unique filename:

    var myFile2 = await myFile1.CopyAsync(ApplicationData.Current.LocalFolder, myFile1.Name, NameCollisionOption.GenerateUniqueName);
    

    To move a file with a unique filename in the destination location:

    await myFile.MoveAsync(ApplicationData.Current.LocalFolder, myFile.Name, NameCollisionOption.GenerateUniqueName);
    

    To rename a file with a unique filename in the destination location:

    await myFile.RenameAsync(myFile.Name, NameCollisionOption.GenerateUniqueName);
    

提交回复
热议问题