Developer
Developer

Reputation: 8636

Saving file with the same name

I have used this to save my file

string m_strDate = DateTime.Now.ToString("MM/dd/yyyy");
m_strDate = m_strDate.Replace("/", "");
strPath += "/FileHeader_" + m_strDate + ".txt";

So as per this I can save a file per day. But if I create for another time the data in that text file is getting replaced by the new one. Now what I need is I would like to save my file with some name along with date and a number like

"/FileHeader_1" + m_strDate + ".txt"

and so on.

Upvotes: 3

Views: 3716

Answers (4)

Oleksii Prykhodko
Oleksii Prykhodko

Reputation: 31

    public string AddToFileNameUniqueNumber(string fileFullPath)
    {
        if (string.IsNullOrWhiteSpace(fileFullPath))
        {
            throw new ArgumentNullException(nameof(fileFullPath), "Path can't be null or empty.");
        }
        if (File.Exists(fileFullPath))
        {
            throw new ArgumentException(nameof(fileFullPath), "The specified path does not lead to the file.");
        }

        string fileDirectoryName = Path.GetDirectoryName(fileFullPath);
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileFullPath);
        string fileExtension = Path.GetExtension(fileFullPath);

        string fullFileNameWithUniqueIndex = "";

        for (int i = 1; i < int.MaxValue; i++)
        {
            fullFileNameWithUniqueIndex = Path.Combine(fileDirectoryName, $"{fileNameWithoutExtension} ({i}){fileExtension}");
            if (!File.Exists(fullFileNameWithUniqueIndex))
            {
                break;
            }
        }

        return fullFileNameWithUniqueIndex;
    }

Upvotes: 0

LukeH
LukeH

Reputation: 269318

string head = Path.Combine(strPath, "FileHeader_");
string tail = DateTime.Now.ToString("MMddyyyy") + ".txt";

int index = 1;
string fileName = head + tail;

while (File.Exists(fileName))
{
    fileName = head + index + tail;
    index++;
}

Upvotes: 0

Draco Ater
Draco Ater

Reputation: 21226

strPath = "/FileHeader_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";

or check if the file exists:

strPath = "/FileHeader_{0}" + DateTime.Now.ToString("MMddyyyy") + ".txt";
if ( File.Exists( string.format( strPath, "" ) ){
  int i = 1;
  while( File.Exists(string.format( strPath, i ) ){ i++ ; }
  strPath = string.Format(strPath, i);
}
else {
  strPath = string.format( strPath, "" );
}

Upvotes: 4

Itay Karo
Itay Karo

Reputation: 18286

string fileName = "/FileHeader_" + m_strDate + ".txt";
if (File.Exists(fileName))
{
  int index = 1;
  fileName = "/FileHeader_" + index + m_strDate + ".txt";
  while (File.Exists(fileName))
    fileName = "/FileHeader_" + ++index + m_strDate + ".txt";
}

Upvotes: 3

Related Questions