Resolved Get filename from custom template

DjGrego

Member
Joined
Nov 21, 2021
Messages
23
Programming Experience
Beginner
I have a string that holds a filename template. (taken from a xml file value made by another program)

Inside that string there is %m or %mm style templates.

For example:

XXXX-FM-DA-%m-%d-%yyyy-OPX2.txt

or

XXXX-AM-DA-%d.%m.%yy-OPX2.txt

How could I output a string, replacing the custom date values (with today's values) but keep the rest of the text?

XXXX-FM-DA-11-21-2021-OPX2.txt

Thank you for any suggestions.

Greg
 
Solution
What are the allowable template placeholders? Is it only ever these:
C#:
%m
%d
%yyyy
%yy

or are there other allowable placeholders allowed?

Anyway, if the the template placeholders all correspond to the C# custom date/time string format specifiers (see below), then I would escape all the non-placeholder characters (if needed), and then just remove the '%' storing the result into a string variable (ex. escapedTemplate). From there pass that to DateTime.Now.ToString(escapedTemplate).

Moved to C# General since nothing here is Visual Studio specific.
 
What are the allowable template placeholders? Is it only ever these:
C#:
%m
%d
%yyyy
%yy

or are there other allowable placeholders allowed?

Anyway, if the the template placeholders all correspond to the C# custom date/time string format specifiers (see below), then I would escape all the non-placeholder characters (if needed), and then just remove the '%' storing the result into a string variable (ex. escapedTemplate). From there pass that to DateTime.Now.ToString(escapedTemplate).

 
Solution
I found a solution sort of based on your suggestion. Thank you:

Solution:
string s = "ABCD-FM-DA-%m-%d-%yyyy-OGX2.txt";
StringBuilder sb = new StringBuilder(s);

sb.Replace("%yyyy", DateTime.Now.ToString("yyyy"));
sb.Replace("%yy", DateTime.Now.ToString("yy"));
sb.Replace("%mmmm", DateTime.Now.ToString("MMMM"));
sb.Replace("%mmm", DateTime.Now.ToString("MMM"));
sb.Replace("%mm", DateTime.Now.ToString("MM"));
sb.Replace("%m", DateTime.Now.Month.ToString());
sb.Replace("%dddd", DateTime.Now.ToString("dddd"));
sb.Replace("%ddd", DateTime.Now.ToString("ddd"));
sb.Replace("%dd", DateTime.Now.ToString("dd"));
sb.Replace("%d", DateTime.Now.ToString("%d"));

Console.WriteLine(sb);

The funny thing is:
sb.Replace("%mm", DateTime.Now.ToString("MM")); should have returned 11 but instead returned 11-21-2021.
I changed it to sb.Replace("%m", DateTime.Now.Month.ToString()); and it worked. Weird.
 
I suspect that you may have had a typo while you were cycling doing edit-build-run, but this works just fine for me:
C#:
Console.WriteLine(DateTime.Now.ToString("MM"));

DotNetFiddle: https://dotnetfiddle.net/iUnmTR
 
Last edited by a moderator:
Back
Top Bottom