Search code examples
c#filenames

Custom user defined file name format in c#


The requirement is that a user can choose a file name format from predefined tags.

Example InvoiceNo Date VendorName

if user chooses InvoiceNo-Date-Vendorname then the file name should be generated like: 001-20170512-ABCElectronics

if user chooses InvoiceNo-Date then the file name should be generated like: 001-20170512

if user chooses VendorName-InvoiceNo-Date then the file name should be generated like: ABCElectronics-001-20170512

format.Replace("InvoiceNo",generateNo()); Will .Replace first check if string exists and then executes the 2nd parameter? The 2nd parameter could be a long running method.

Should I first check if tag exists in the file format and then replace or just use .Replace method without checking?

Thanks


Solution

  • simple way:

    input = input.Replace("InvoiceNo",generateInvo());
    input = input.Replace("Date",generateDate());
    input = input.Replace("Vendorname",generateVendor());
    

    this will change the first occurrence of those strings for the code you desire. You can also do this in one line like x.Replace(y0,y1).Replace(z0,z1); if you wish.