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

前端 未结 18 778
没有蜡笔的小新
没有蜡笔的小新 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:21

    Instead of poking the disk a number of times to find out if it has a particular variant of the desired file name, you could ask for the list of files that already exist and find the first gap according to your algorithm.

    public static class FileInfoExtensions
    {
        public static FileInfo MakeUnique(this FileInfo fileInfo)
        {
            if (fileInfo == null)
            {
                throw new ArgumentNullException("fileInfo");
            }
    
            string newfileName = new FileUtilities().GetNextFileName(fileInfo.FullName);
            return new FileInfo(newfileName);
        }
    }
    
    public class FileUtilities
    {
        public string GetNextFileName(string fullFileName)
        {
            if (fullFileName == null)
            {
                throw new ArgumentNullException("fullFileName");
            }
    
            if (!File.Exists(fullFileName))
            {
                return fullFileName;
            }
            string baseFileName = Path.GetFileNameWithoutExtension(fullFileName);
            string ext = Path.GetExtension(fullFileName);
    
            string filePath = Path.GetDirectoryName(fullFileName);
            var numbersUsed = Directory.GetFiles(filePath, baseFileName + "*" + ext)
                .Select(x => Path.GetFileNameWithoutExtension(x).Substring(baseFileName.Length))
                .Select(x =>
                        {
                            int result;
                            return Int32.TryParse(x, out result) ? result : 0;
                        })
                .Distinct()
                .OrderBy(x => x)
                .ToList();
    
            var firstGap = numbersUsed
                .Select((x, i) => new { Index = i, Item = x })
                .FirstOrDefault(x => x.Index != x.Item);
            int numberToUse = firstGap != null ? firstGap.Item : numbersUsed.Count;
            return Path.Combine(filePath, baseFileName) + numberToUse + ext;
        }
    }    
    

提交回复
热议问题