Saving File with different name if the file name already exist?

I am using write range activity to write data table to an excel file. I am giving the name of file in this format- 20210527.xlsx, i.e., yyyyMMdd.xlsx

The problem with this is, if on the same day the process is run more than once then the file will be overwritten. I do not want this. If the process is run 2nd time then the name of the file should be 20210527_1.xlsx, for 3rd time it should be 20210527_2.xlsx. How can this task be accomplished in the best possible way? With best I mean using very less activities and without complicating the workflow. If there is vb.net method to do so or something like that please suggest. I have come up with a solution of using Path Exist activity, while Loop and concatenating the file name string variable with “_countVariable”.

Is there any other better approach?

1 Like

Hi @kumar.varun2

Instead of counter you can use the timestamp along with the date so every time it will create a new excel file.

Hope this help

Thank you,
Prashant

Use Directory.GetFiles to see if there are any files with the current date and then decide if you should add anything

1 Like

He is trying to avoid this.

have to be in the format specified. Thanks by the way

Try this…

Now.Tostring(“yyyyMMdd hhmmss”)

Hope this helps :slight_smile:

have to be in this format only yyyyMMdd_count

1 Like

If you want this to occur @kumar.varun2,

Do a file exist before saving the file, if yes increase the counter and recheck…

Put this in loop till you get something that doesn’t exist

This will be simple and quick to implement :slight_smile:

I was asking for another approach.

If possible

Hi @kumar.varun2,

Please try this xaml:

FileExistsRename.xaml (5.4 KB)

Tried with vb.net, test with your file name.

Thanks!

Why have you used - System.Threading.Interlocked.Increment(count) ?

Thanks

@kumar.varun2 I think to increase the counter only

1 Like

To increment the counter value - fastest and safest way in c#.

How about using Append Range instead of Write Range? Then if the file already exists, it’ll just add to it. If it doesn’t exist, it’ll create it and write to it.

What is atomic operation?

Append will not write the header in file.

Then write code to check if the file exists, and if it doesn’t then add a header row to the file before calling Append Row.

Need to keep separate files. I have used the approach suggested by you for monthly data file. Appending daily data in monthly data file.

Thanks

Could this be done through LINQ or extension methods? @ppr please help