Way to get unique filename if specified filename already exists (.NET)

前端 未结 4 1316
醉酒成梦
醉酒成梦 2021-01-20 00:00

Is there a built in .NET function to get a unique filename if a filename already exists? So if I try and save MyDoc.doc and it already exists, the file will sav

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-20 00:52

    EDIT:

    Here's another solution I came up with after Steven Sudit's comment:

    static void Main(string[] args)
    {
        CopyFile(new FileInfo(@"D:\table.txt"), new FileInfo(@"D:\blah.txt"));
    }
    
    private static void CopyFile(FileInfo source, FileInfo destination)
    {
        int attempt = 0;
    
        FileInfo originalDestination = destination;
    
        while (destination.Exists || !TryCopyTo(source, destination))
        {
            attempt++;
            destination = new FileInfo(originalDestination.FullName.Remove(
                originalDestination.FullName.Length - originalDestination.Extension.Length)
                + " (" + attempt + ")" + originalDestination.Extension);
        }
    }
    
    private static bool TryCopyTo(FileInfo source, FileInfo destination)
    {
        try
        {
            source.CopyTo(destination.FullName);
            return true;
        }
        catch
        {
            return false;
        }
    }
    

提交回复
热议问题