XamDev
XamDev

Reputation: 3657

Date time is not changing in c#

We are trying to form image name using below method and this method is called in for loop. We have used DateTime.UtcNow to append date time to image name.

However, our issue is for all images the same date time is getting appended, even though we have tried to use seconds and milliseconds to differentiate the image name.

As the same names are getting formed, while uploading the images, the images are getting replaced and only one image is uploaded.

Below is our code which is forming the image name.

public string FormImageName(string issuetype)
        {
            string fileName = issuetype +
                              "_" +
                              DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss:fff tt") +
                              ".jpeg";

            return fileName;
        }

Any help on this appreacited !

Upvotes: 0

Views: 146

Answers (2)

dperez
dperez

Reputation: 594

Why not use an index in your loop? As the method is so fast you end up with repeated date/time.

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(FormImageName("bug", i));
        }

        Console.ReadKey();
    }

    static string FormImageName(string issuetype, int index)
    {
        string fileName = $"{issuetype}_{DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture)}_{index}.jpeg";
      
        return fileName;
    }
}

Upvotes: 3

Nicolas Fontes
Nicolas Fontes

Reputation: 39

Try to create a specific method to do it. You can send how many pictures you have or send the list of the pictures and do a foreach to concat a "index" for each photo.

static List<string> GenerateNames(int numberOfImages, string issuetype)
        {
            List<string> names = new List<string>();
            for (int i = 0; i < numberOfImages; i++)
                names.Add($"{numberOfImages}_{issuetype}_" +
                    $"{DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss:fff tt")}.jpeg");

            
            return names;
        }

enter image description here

Upvotes: 0

Related Questions