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

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

    /// 
    /// Create a unique filename for the given filename
    /// 
    /// A full filename, e.g., C:\temp\myfile.tmp
    /// A filename like C:\temp\myfile633822247336197902.tmp
    public string GetUniqueFilename(string filename)
    {
        string basename = Path.Combine(Path.GetDirectoryName(filename),
                                       Path.GetFileNameWithoutExtension(filename));
        string uniquefilename = string.Format("{0}{1}{2}",
                                                basename,
                                                DateTime.Now.Ticks,
                                                Path.GetExtension(filename));
        // Thread.Sleep(1); // To really prevent collisions, but usually not needed
        return uniquefilename;
    }
    

    As DateTime.Ticks has a resolution of 100 nanoseconds, collisions are extremely unlikely. However, a Thread.Sleep(1) will ensure that, but I doubt that it's needed

提交回复
热议问题