Izzy
Izzy

Reputation: 6866

Changing file name

Consider the following code snippet

public static string AppendDateTimeToFileName(this string fileName)
{
   return string.Concat(
      Path.GetFileNameWithoutExtension(fileName),
      DateTime.Now.ToString("yyyyMMddHHmmssfff"),
      Path.GetExtension(fileName));
}

This basically puts a date time stamp on any file that is being uploaded by the users. Now this works great is the file name is something like

Now I'm trying to change this method so if the file name is something like

I want the file name to become

If there an easy soltuion for this with regex or similar or do I have to re-write the method again and check each of those values one by one.

Upvotes: 1

Views: 60

Answers (1)

Alex K.
Alex K.

Reputation: 175906

return string.Concat(
      Regex.Replace(Path.GetFileNameWithoutExtension(fileName), @" - Copy\s*\(\d+\)", "-Copy-", RegexOptions.IgnoreCase),
      DateTime.Now.ToString("yyyyMMddHHmmssfff"),
      Path.GetExtension(fileName));

This matches any number of digits and is a global replace.

Upvotes: 3

Related Questions