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

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

    This method will add a index to existing file if needed:

    If the file exist, find the position of the last underscore. If the content after the underscore is a number, increase this number. otherwise add first index. repeat until unused file name found.

    static public string AddIndexToFileNameIfNeeded(string sFileNameWithPath)
    {
        string sFileNameWithIndex = sFileNameWithPath;
    
        while (File.Exists(sFileNameWithIndex)) // run in while scoop so if after adding an index the the file name the new file name exist, run again until find a unused file name
        { // File exist, need to add index
    
            string sFilePath = Path.GetDirectoryName(sFileNameWithIndex);
            string sFileName = Path.GetFileNameWithoutExtension(sFileNameWithIndex);
            string sFileExtension = Path.GetExtension(sFileNameWithIndex);
    
            if (sFileName.Contains('_'))
            { // Need to increase the existing index by one or add first index
    
                int iIndexOfUnderscore = sFileName.LastIndexOf('_');
                string sContentAfterUnderscore = sFileName.Substring(iIndexOfUnderscore + 1);
    
                // check if content after last underscore is a number, if so increase index by one, if not add the number _01
                int iCurrentIndex;
                bool bIsContentAfterLastUnderscoreIsNumber = int.TryParse(sContentAfterUnderscore, out iCurrentIndex);
                if (bIsContentAfterLastUnderscoreIsNumber)
                {
                    iCurrentIndex++;
                    string sContentBeforUnderscore = sFileName.Substring(0, iIndexOfUnderscore);
    
                    sFileName = sContentBeforUnderscore + "_" + iCurrentIndex.ToString("000");
                    sFileNameWithIndex = sFilePath + "\\" + sFileName + sFileExtension;
                }
                else
                {
                    sFileNameWithIndex = sFilePath + "\\" + sFileName + "_001" + sFileExtension;
                }
            }
            else
            { // No underscore in file name. Simple add first index
                sFileNameWithIndex = sFilePath + "\\" + sFileName + "_001" + sFileExtension;
            }
        }
    
        return sFileNameWithIndex;
    }
    

提交回复
热议问题