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

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

    Here's one that decouples the numbered naming question from the check of the filesystem:

    /// 
    /// Finds the next unused unique (numbered) filename.
    /// 
    /// Name of the file.
    /// Function that will determine if the name is already in use
    /// The original filename if it wasn't already used, or the filename with " (n)"
    /// added to the name if the original filename is already in use.
    private static string NextUniqueFilename(string fileName, Func inUse)
    {
        if (!inUse(fileName))
        {
            // this filename has not been seen before, return it unmodified
            return fileName;
        }
        // this filename is already in use, add " (n)" to the end
        var name = Path.GetFileNameWithoutExtension(fileName);
        var extension = Path.GetExtension(fileName);
        if (name == null)
        {
            throw new Exception("File name without extension returned null.");
        }
        const int max = 9999;
        for (var i = 1; i < max; i++)
        {
            var nextUniqueFilename = string.Format("{0} ({1}){2}", name, i, extension);
            if (!inUse(nextUniqueFilename))
            {
                return nextUniqueFilename;
            }
        }
        throw new Exception(string.Format("Too many files by this name. Limit: {0}", max));
    }
    

    And here's how you might call it if you are using the filesystem

    var safeName = NextUniqueFilename(filename, f => File.Exists(Path.Combine(folder, f)));
    

提交回复
热议问题