原文链接:http://www.oschina.net/code/snippet_4873_1460
做了一点调整
将一个文档保存为 a.txt 时,发现此文件已经存在,则自动保存为 a(1).txt,如果不存在,仍为a.txt
/// <summary>
/// Generates a new path for duplicate filenames.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
private string GetNewPathForDupes( string path )
{
string directory = Path.GetDirectoryName( path );
string filename = Path.GetFileNameWithoutExtension( path );
string extension = Path.GetExtension( path );
int counter = 1;
string newFullPath=path;
while ( System.IO.File.Exists( newFullPath ) )
{
string newFilename = "{0}({1}){2}".FormatWith( filename, counter, extension );
newFullPath = Path.Combine( directory, newFilename );
counter++;
}
return newFullPath;
}