C#: How would you make a unique filename by adding a number?

前端 未结 18 775
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 11:46

I would like to create a method which takes either a filename as a string or a FileInfo and adds an incremented number to the filename if the file

18条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 12:14

        private async Task CreateBlockBlob(CloudBlobContainer container,  string blobNameToCreate)
        {
            var blockBlob = container.GetBlockBlobReference(blobNameToCreate);
    
            var i = 1;
            while (await blockBlob.ExistsAsync())
            {
                var newBlobNameToCreate = CreateRandomFileName(blobNameToCreate,i.ToString());
                blockBlob = container.GetBlockBlobReference(newBlobNameToCreate);
                i++;
            }
    
            return blockBlob;
        }
    
    
    
        private string CreateRandomFileName(string fileNameWithExtension, string prefix=null)
        {
    
            int fileExtPos = fileNameWithExtension.LastIndexOf(".", StringComparison.Ordinal);
    
            if (fileExtPos >= 0)
            {
                var ext = fileNameWithExtension.Substring(fileExtPos, fileNameWithExtension.Length - fileExtPos);
                var fileName = fileNameWithExtension.Substring(0, fileExtPos);
    
                return String.Format("{0}_{1}{2}", fileName, String.IsNullOrWhiteSpace(prefix) ? new Random().Next(int.MinValue, int.MaxValue).ToString():prefix,ext);
            }
    
            //This means there is no Extension for the file and its fine attaching random number at the end.
            return String.Format("{0}_{1}", fileNameWithExtension, new Random().Next(int.MinValue, int.MaxValue));
        }
    

    I use this code to create a consecutive _1,_2,_3 etc.. file name everytime a file exists in the blob storage.

提交回复
热议问题