Generate unique file name with number in parenthesis

/, asp.net, Blog, C#/Generate unique file name with number in parenthesis

You must have noticed that if a file name is duplicate when you copy paste a file in windows or download a file then windows appends to the file name a number within parenthesis.

There are various code snippets around the web to generate a file name with a number in parenthesis when saving files. Below is the code I’m using in my project because simply is better the most of the source codes I found on the web and it fills the gap in between numbers.

If there are files in a directory like myfile (1).txt, myfile (2).txt, myfile (4).txt and you try to save a new file it will name the filename as myfile (3).ext before increasing the counter.

private string GetFilename(string fullpath)
{
	if (File.Exists(fullpath))
	{
		string fileNameOnly = Path.GetFileNameWithoutExtension(fullpath);
		string extension = Path.GetExtension(fullpath);
		string path = Path.GetDirectoryName(fullpath);
		List<string> files = Directory.GetFiles(path, string.Format("{0} (*){1}", fileNameOnly, extension)).ToList();
		Regex pattern = new Regex(@"\d+", RegexOptions.RightToLeft);

		int incrementalNo = 1;
		List<int> sequence = files.Select(f => int.Parse(pattern.Match(f.ToString()).Groups[0].Captures[0].Value)).ToList();

		if (sequence.Count >0 && sequence.Max() > sequence.Count)
			incrementalNo = Enumerable.Range(1, files.Count).Except(sequence).First();
		else
			incrementalNo =  sequence.Count +1;

		//int incrementalNo = files.Count() + 1;
		fullpath = Path.Combine(path, string.Format("{0} ({1}){2}", fileNameOnly, incrementalNo++, extension));
	}


	return fullpath;
}

I would be very much interested to hear from you on how you handle it.

2017-03-05T13:56:37+00:00 November 30th, 2016|.net, asp.net, Blog, C#|0 Comments

Leave A Comment