Search code examples
c#datetimefilenames

Saving Filename based on time


I'm making a basic program, and when it comes to saving data I'm trying to put it into a .txt - which is working just fine. Problem is, I can't save the seconds/hours in addition to the date, so my solution was to just get the date and then put 1, 2, 3 respectively on most recent files. The code I made was:

static string FileName()
{
    string fileName = "";
    char last = ' ';
    int lastDigit = 0;
    string lastDigitString = "";
    string directory = Directory.GetCurrentDirectory(); 
    if (File.Exists(DateTime.Now.Date.ToString("dd-MM-yy" + "1") + ".txt"))
    {
        fileName = Path.GetFileNameWithoutExtension(newFileName + ".txt");
        last = fileName[fileName.Length - 1];
        lastDigit = int.Parse(last.ToString());
        lastDigit = lastDigit + 1;
        lastDigitString = lastDigit.ToString();
        newFileName = fileName + lastDigitString;
    }
    else
    {
        newFileName = DateTime.Now.Date.ToString("dd-MM-yy" + "1");
    }

    return fileName;
}

with newFileName being defined as a global variable at the top.

public static string newFileName = DateTime.Now.Date.ToString("dd-MM-yy" + "1");

I've been messing around with some things might be out of place. My solution was to get the filename and then take off the .txt - which would then leave me with just the name where I get the last digit of the name and then increase it by one, then add it to the end of a new file name. It goes 'FileName1' then 'FileName12' which is what I hoped to get, but once there it just keeps adding to 'FileName12' which is obviously from the appending set to true, but I hoped for a 'FileName123'.


Solution

  • Is there a requirement not to use the Hour/Minute/Second for your file name? You are using DateTime.Now.Date.ToString(..), which will strip out the hour/minute/second data. You can use DateTime.Now.ToString(..) to reserve the sub-day data.

    You'll need to provide your own format string to generate a file-name-friendly output.