Can I use Format instead of using substring?

Using a memory profile on my C# desktop app I have found that strings are not being released from memory causing a slow and gradual buildup.

I have this code:

var ToYYYMMDDHHMMSS = "YYYMMDDHHMMSS";
var toYR = ToYYYMMDDHHMMSS.Substring(0, 4);
var toMN = ToYYYMMDDHHMMSS.Substring(4, 2);
var toDY =ToYYYMMDDHHMMSS.Substring(6, 2);
var toHR = ToYYYMMDDHHMMSS.Substring(8, 2);
var toMI = ToYYYMMDDHHMMSS.Substring(10, 2);
var motionPath = string.Format("{0}\\Catalogues\\{1}\\{2}\\{3}\\{4}\\{5}\\{6}", Shared.MOTION_DIRECTORY, camIndex, toYR, toMN, toDY, toHR, toMI);

Is there an alternative to using the substring? Can I use String.Format someway to get my desired result?

NB I am so sorry for my poor phrasing of my question..

var ToYYYMMDDHHMMSS = "YYYMMDDHHMMSS";

I should have added that "YYYMMDDHHMMSS" is a timestamp that always changes {apologies)

Jon Skeet
people
quotationmark

My guess is that your real code has a value of something like 20150225071945 - so not actually the literal YYYYMMDDHHMMSS. If that's the case, I would parse the value as a DateTime rather than extracting substrings:

DateTime dateTime = DateTime.ParseExact(text, "yyyyMMddHHmmss",
                                        CultureInfo.InvariantCulture);
var motionPath = string.Format(@"{0}\Catalogues\{1:yyyy\\MM\\dd\\HH\\mm\\ss}",
                               Shared.MOTION_DIRECTORY, dateTime);

Note that the format string itself is a verbatim string literal, so you don't need to escape backslashes - but I've got \\ in the format string for the DateTime because the DateTime formatting code will treat \ as an escape.

An alternative would be to format each part of the date separately:

var motionPath = string.Format(@"{0}\Catalogues\{1:yyyy}\{1:MM}\{1:dd}\{1:HH}\{1:mm}\{1:ss}",
                               Shared.MOTION_DIRECTORY, dateTime);

Or use Path.Combine:

var motionPath = Path.Combine(Shared.MOTION_DIRECTORY,
                              "Catalogues",
                              dateTime.ToString("yyyy"),
                              dateTime.ToString("MM"),
                              dateTime.ToString("dd"),
                              dateTime.ToString("HH"),
                              dateTime.ToString("mm"),
                              dateTime.ToString("ss"));

people

See more on this question at Stackoverflow