Way to get unique filename if specified filename a

2019-02-23 19:32发布

问题:

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 save with name MyDoc(1).doc, the same way a browser download works for example.

If not, what is the most efficient way to achieve this result?

I am using the File.Move function at the moment btw.

回答1:

check the name against Regex *.\(\d+\), if it doesn't match, add (1), if it matches increment the number in brackets.



回答2:

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;
    }
}


回答3:

I don't know, but it's not hard to build one yourself:

if filename does not exists then 
    save file as filename
else
n = 1
while filename(n) exists: 
    n += 1
save file as filename(n)


回答4:

As the other answers shows, there are multiple ways of doing this, but one thing to be aware of is if other processes than your can create files you have to be careful, since if you check that a filename is available, by the time you save your new file, some other process might already have saved a file using that name and you'll overwrite that file.