1

Not sure how to ask this. I am writing a CONSOLE app in C#. With each run I plan to create an output txt file. However I need some expression that will give an unique name with each run ( and also this name must remain the same through out the run ) I can use YYYYMMDDSS but this can change with each call. So you see what I mean. It should be something like Session ID ( I don't know what method/function will give me this ). Help please ? ( I am new to C# )

abatishchev
  • 98,240
  • 88
  • 296
  • 433

2 Answers2

3

If you want the identifier to change on each execution, but be consistent for the life of the program, you probably want to generate it once and store the result.

One way is to store it in a readonly static property:

public static class RuntimeIdentifier
{
    public static string Value { get; } = DateTime.Now.ToString("yyyyMMddhhmmss");

    // Notice this is NOT the same as:
    //
    //   public static string Value { get { return DateTime.Now.ToString("yyyyMMddhhmmss"); } }
    //
    // which will return a NEW value each time you access it
}

Another way would be to use Lazy<T>, which computes a value the first time you access it, and returns the same value each time after that.

public static class RuntimeIdentifier
{
    public static Lazy<string> _identifier = new Lazy<string>(() => DateTime.Now.ToString("yyyyMMddhhmmss"));

    public static string GetValue()
    {
        return _identifier.Value;
    }
}

If it's important that the value be generated immediately when the app is started, you can generate and save it explicitly:

class Program
{
    public static void Main()
    {
        RuntimeIdentifier.Value = DateTime.Now.ToString("yyyyMMddhhmmss");

        // ...
    }
}

public static class RuntimeIdentifier
{
    public static string Value { get; set; }
}
Stephen Jennings
  • 12,494
  • 5
  • 47
  • 66
0

Your scenario is not totally clear but if you are just trying to create a txt file with unique name each time you run your application than you should use Path.GetRandomFileName() for that matter. Or just look how it's implemented and adapt it to your needs.

Kostya
  • 849
  • 5
  • 14