C Method for Automatic Generation of New Files with Duplicate Names When Saving Files

  • 2021-07-22 11:02:14
  • OfStack

In this paper, the method of automatically generating new files with duplicate names when saving files is described by C #. Share it for your reference. The details are as follows:

When you save a document as a. txt and find that the file already exists, automatically save it as a (1). 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;
  do
  {
  string newFilename = "{0}({1}).{2}".FormatWith( filename, counter, extension );
  newFullPath = Path.Combine( directory, newFilename );
  counter++;
  } while ( System.IO.File.Exists( newFullPath ) );
  return newFullPath;
}

I hope this article is helpful to everyone's C # programming.


Related articles: