delphi,delphi-2010 , Function to increment filename

Function to increment filename


Tag: delphi,delphi-2010

I'm trying to make a function that can increment a filename. If last char of the string is a number then increment it. If last char is a letter then add _1 or _2 or _3(increment this also). I have to be sure the filename is unique but i cannot use datetime inside filename because all the filenames must be <32 chars without extension.

EX: Apple_99.txt =>Apple_100
Ex: Apple_173 => Apple_174
EX: This_is_my_first_text.txt => This_is_my_first_text_1.txt
Ex: This_is_my_first_text_9.txt => This_is_my_first_text_10.txt

I need to use this in order to rename a file an then upload it to a ftp server. I've found a function that can do something like this but it only works if the filename contains only uppercase.How can I modify this function in order to access lowercase an uppercase string?

Here is the function:

    function IncStr(Str: String; Amount: Integer; Index: Integer = -1): String;
     MIN_VAL = 65; // 'A'
     MAX_VAL = 90; // 'Z'
     Digit, ToAdd, ToCarry: Integer;

     if (Index = 0) and (Amount > 0) then
       Result := Char(MIN_VAL + Amount - 1) + Str;

     if Index = -1 then Index := Length(Str);

     ToCarry := 0;

     Digit := Ord(Str[Index]);

     while not (Digit in [MIN_VAL..MAX_VAL]) do
       Digit := Ord(Str[Index]);

     ToAdd := Digit + Amount;

     while (ToAdd > MAX_VAL) do
       Dec(ToAdd, 26);

     Result := Str;
     Result[Index] := Char(ToAdd);

     if (ToCarry > 0) then
      Result := IncStr(Result, ToCarry, Index - 1);


    procedure TForm1.Button1Click(Sender: TObject);
     S: String;   // holds string to increment
     C: Integer;  // amount to increment by
     // make sure that Edit1 starts with a valid character
     // i.e. 'A' to 'Z'
     S := Edit1.Text;
     C := StrtoIntDef(Edit2.Text, 0);
     // test it, place result in Edit3
     Edit3.Text := IncStr(S, C);
       Example data:

         Edit1 := AAZ
         Edit2 := 2
       = Edit3 := ABB

         Edit1 := BZY
         Edit2 := 3
       = Edit3 := CAB

         Edit1 := ZZZ
         Edit2 := 1
       = Edit3 := AAAA

         Edit1 := AA-AC
         Edit2 := 3
       = Edit3 := AA-AF

         Edit1 := AA/Z
         Edit2 := 5
       = Edit3 := AB/E

       ... etc

       Here's one to try too :-)
         Edit1 := ZZZ
         Edit2 := 264172

Thank you!


Like so many programming problems, the key is to break the problem down into small pieces. First of all, let's write a function to decode the original file name into its constituent parts:

procedure DecodeFileName(const Input: string; out Stem, Ext: string; out Number: Integer);
  P: Integer;
  Ext := TPath.GetExtension(Input);
  Stem := TPath.GetFileNameWithoutExtension(Input);
  Number := 0;

  P := Stem.LastIndexOf('_');
  if P = -1 then begin

  if TryStrToInt(Stem.Substring(P+1), Number) then begin
    Stem := Stem.Substring(0, P);

The following demonstrates how this works:

DecodeFileName('test.txt', Stem, Ext, Number);
Writeln(Stem, ', ', Number, ', ', Ext);

DecodeFileName('test_dd.txt', Stem, Ext, Number);
Writeln(Stem, ', ', Number, ', ', Ext);

DecodeFileName('test_23.txt', Stem, Ext, Number);
Writeln(Stem, ', ', Number, ', ', Ext);

The output is:

test, 0, .txt
test_dd, 0, .txt
test, 23, .txt

So now you can make a new filename like this:

function IncrementedFileName(const FileName: string): string;
  Stem, Ext: string;
  Number: Integer;
  DecodeFileName(FileName, Stem, Ext, Number);
  Result := Format('%s_%d%s', [Stem, Number+1, Ext]);

And then we can see how that performs:


The output is:


If you don't have access to the string helper methods then you can code it like this:

procedure DecodeFileName(const Input: string; out Stem, Ext: string; out Number: Integer);
  P: Integer;
  Ext := TPath.GetExtension(Input);
  Stem := TPath.GetFileNameWithoutExtension(Input);
  Number := 0;

  P := LastDelimiter('_', Stem);
  if P = 0 then begin

  if TryStrToInt(Copy(Stem, P+1, MaxInt), Number) then begin
    Stem := Copy(Stem, 1, P-1);

I have not executed this final function, so do not be surprised if it has errors.


How to remove duplicates in ListBox?

I use this code to remove duplicates: procedure TForm1.RemoveDuplicates(StrList : TStringList); var NoDuplicate: TStringList; i: Integer; begin NoDuplicate := TStringList.Create; try NoDuplicate.Sorted := True; NoDuplicate.Duplicates := dupIgnore; /// for i := 0 to StrList.Count - 1 do NoDuplicate.Add(StrList[i]) ; /// NoDuplicate.Sorted:= False; StrList.Assign(NoDuplicate) ; finally NoDuplicate.Free; end; end; It works...

Setting “Server” programatically with a TFDConnection

TFDConnection.Params.Server is not a valid published property in Delphi XE7. How can I set the server location programatically? I have 2 MySQL servers (test and production) that are at different ip's and based on what I am doing in the application, I want to easily switch back and forth between...

HasValidFileNameChars fails for UNC files

For me HasValidFileNameChars function (in Delphi XE7) returns false for UNC files: B:= IOUtils.TPath.HasValidFileNameChars('\\ETA-PC\tests\test.ini', FALSE) B is false now This means that if you try to validate the filename that I show in my test (yes the file is real and as you can see its name is correct) HasValidFileNameChars...

How to get enabled property of a control?

In Delphi it is possible to get the process name and class name of any control which is clicked system wide via windows api. process name: GetWindowThreadProcessId(Hwnd, ProcessId) by process ID one can get to the process name class name: SetLength(ClassName, 255); SetLength(ClassName, GetClassName(Hwnd, pchar(ClassName), 255)); Is there an easy...

Referring to interface versus to an object implemeting it?

Given the following declarations: var XML:IXMLDocument; and var XML:TXMLDocument; What's the difference of working with the XML variable from end-user point of view? What's preferred?...

Custom component controls keep re-creating

I'm a newbie in Firemonkey/custom controls so sorry if this is a banal question or a duplicate one but I'm stuck and can't figure it out. Here's the code of my custom control unit swScheduler; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.StdCtrls, FMX.Calendar, FMX.Objects; type TswScheduler = class(TControl) private {...

Does “enable runtime themes” affect performance?

I've recently changed "enable runtime themes" value in the project options and I'm wondering if it's value affects application's performances and, in case, in which manner? Hope someone can clarify me this point.

Firemonkey ListView item indexes not updating

I'm using a TListView in Firemonkey. On startup, I create 3 list view headers and keep references to them for future use (specifically inserting items below each header). FItemHeader:= LV.Items.Add; FItemHeader.Purpose:= TListItemPurpose.Header; FItemHeader.Text:= 'Items'; FChargeHeader:= LV.Items.Add; FChargeHeader.Purpose:= TListItemPurpose.Header; FChargeHeader.Text:= 'Charges'; FPaymentHeader:= LV.Items.Add; FPaymentHeader.Purpose:= TListItemPurpose.Header; FPaymentHeader.Text:= 'Payments'; Then, I've added a...

See when Delphi Twebbrowser starts loading a page

I am using delphi's TWebbrowser to navigate to a php file I created. I have a loading screen I would like to show when the page is loading or processing commands. How can I detect when it is being refreshed or still loading. currently I am using the ondocumentcomplete to...

Component event detection in Delphi

I am developing a DataAware component and executing some code after the database is open. This is the code I have at the moment: TMyDataAwareComponent = class(TDataAwareComponent) private { Private declarations } procedure ToBeExecutedOnAfterOpen(DataSet: TDataSet); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; end;...

Delphi generic frame

I'm still here with a questione about Delphi frames. I would like to create an application that use various type of frames in order to manage different database tables, so trying to understand how to do this kind of task I've create a simple Delphi Form: unit main; interface uses...

Issues with AES Encryption using SynCrypto

Am trying to encrypt a file using SynCrypto.pas with AES 256, but it fails if I try to encrypt a file whose size is not a multiple of 16 bytes. The decrypted data contains junk. Example: Original string in txt file we are testing the file Encrypted String [ù[„|wáî}f *!4ìÙw¬•ü¨s...

Why Application.OnException never runs?

Problem summary: The method assigned to Application.OnException never runs when an unhandled exception occurs. I create a blank project with only this unit and place a single button on Unit.dfm (this is based on an official example) : // Unit1.pas // ********* type TForm1 = class(TForm) Button1: TButton; procedure FormCreate(Sender:...

do oncalculate fields in one table using values from another table

I am doing calculations in my KLOG table. However, my PRICES table has the data I need for the calculations in the KLOG table. Example : KLOG table has PRICE_ID field (integer). So does the PRICES table. So I am trying to do something like this (oncalculatefields of the KLOG...

How to correctly have modeless form appear in taskbar

I am trying to achieve the age-old Delphi dream of having a modeless form appear in the taskbar. What is the correct way to have a modeless form appear in the taskbar? Research Effort These are my attempts to solve the problem. There are a lot of things needed to...

Currency Formatting with Delphi

I am trying to writte a code in Delphi, which will be displaying a given number in currency format like this: Now it works if filled whole number and another field until any paramater is updated. I'd be happy to have a code which would displaying a number in currency...

connection refused when I try to connect client with server

I made a basic client / server datasnap applications and it work in local network through http but when I tried to connect from the internet I get connection refused, here are the steps I followed: I set at the server component TDSHTTPService to connect through port no 8081 then...

It is required to free the IShellFolder interface returned by SHGetDesktopFolder ? and how?

I am confused. I want to use the function PathToPidlBind from Jedi JCL and I see that they don't release the IShellFolder interfece reurned by SHGetDesktopFolder after using it. Microsoft docs says: "The calling application is responsible for eventually freeing the interface by calling its IUnknown::Release method.". I tried to...

How to use TThread.Synchronize() to retrieve the text of a TEdit control?

How can I use TThread.Synchronize() to retrieve the text of a TEdit control. Should I assign the TEdit text to a global variable or something?

How can I extract part of a PChar into a string?

During profiling I came across a function that was taking quite a bit of time, but essentially boiled down to this very simple piece of code: function GetSubstring(AInput: PChar; AStart, ASubstringLength: Integer): string; begin Result := Copy(AInput, AStart, ASubstringLength); end; This function returns the expected sub-string, but it doesn't scale...

How to make TDBCheckBox update its DataField immediately after click?

I have a form with several controls where the first one is a TDBCheckBox that is bound to DataField := 'enabled'. When the checkbox is clicked I want all the remaining controls to be enabled / disabled. procedure TMyAdapter.DataSourceDataChange(Sender: TObject; Field: TField); var Enabled: Boolean; begin Enabled := FModel.DataSet['enabled'].AsBoolean; FView.Label1.Enabled...

How to call the original class's code when a class helper is in scope?

I'm doing some unit testing on an improved version of quicksort. The (hopefully) faster version is implemented using: TArrayHelper = class helper for System.Generics.Collections.TArray .... class procedure Sort<T>(var Values: array of T); overload; static; class procedure Sort<T>(var Values: array of T; Comparer: IComparer<T>); overload; static; .... I know for now...

Why can't I use compiler intrinsics in an asm block?

Is this a compiler bug? program Project44; {$APPTYPE CONSOLE} uses System.SysUtils; function Test: integer; asm xor eax,eax add eax,SizeOf(NativeInt); end; begin WriteLn(Test); //Typically outputs 31 or 49 {$ifdef CPUX86} WriteLn('should be 4'); {$else} {$ifdef CPUX64} WriteLn('should be 8'); {$endif}{$endif} ReadLn end. This program outputs all kinds of things, except for...

PasswordChar in Delphi XE8's TMemo

I spent a few hours searching Google to see if anyone had shared their articles, but came up empty-handed. If it's possible, I want to know how to enable/disable the passwordChar in Delphi XE8's TMemo to hide user input like in TEdit. ? Maybe via a checkbox! So when the...

Remove specific XML element in Delphi

I have an xml document looks like this: <?xml version="1.0"?> <Person xmlns:xsi="" xmlns:xsd=""> <ExtensionData /> <Name>ali</Name> <Age>37</Age> <Father> <ExtensionData /> <Name>I</Name> <Age>72</Age> </Father> <Mother> <ExtensionData /> <Name>M</Name> <Age>62</Age> </Mother> </Person> I am using Delphi 7. How can I remove all...

Missing operator or semicolon in Delphi 7

I've got the error message "Missing operator or semicolon" on line 38 of this code: procedure TForm1.SpinEdit1Change(Sender: TObject); begin case SpinEdit1.Value of 1: Label6.Caption('rok'); // line 38 end; end; end. Does somebody know what I am missing? Thank you....

What would the design look like for a class that implements a threaded email sending queue?

So my application is a taxi call dispatch system, in which an operator receives calls over the phone and assigns received calls to a driver. On the Call Details form where the call detail is entered, as soon as the Save button is clicked, the form should close, should send...

Function that returns intersection of two TShapes, including TPaths?

Anyone have any knowledge of a function that returns the intersection TPath for two TShapes? Especially one that returns the intersection TPath of two TPaths. For instance: pthIntersection := PathIntersection(Path1,Path2); ...

Reduce lines, use case?

How to reduce the lines, I could use case? I feel that this code is too large, no way to improve? if valmes.Text = '01' then WebTesta.OleObject.Document.all.Item('expmonth', 0).value := '0'; if valmes.Text = '02' then WebTesta.OleObject.Document.all.Item('expmonth', 0).value := '1'; if valmes.Text = '03' then WebTesta.OleObject.Document.all.Item('expmonth', 0).value := '2'; if valmes.Text...

Delphi Bug in Indy FTP List method?

I'm trying to generate a list of files matching a certain file mask and Indy falls over with this error EidReplyRFCError with message '.': No such file or directory. I've tried several variations and this is the result: FTP.List( aFiles, '', true ); => this works FTP.List( aFiles, '*.*', false...

Odd compilation error message

The following snippet, in XE6 procedure TForm1.Test(CDS : TClientDataSet); var AGuid : TGuid; lResult : Longint; begin lResult := SysUtils.CreateGUID(AGuid); CDS.InsertRecord([AGuid, '', False]); end; produces the error message [dcc32 Error] Unit1.pas(73): E2150 Bad argument type in variable type array constructor Fwiw, in discovering this, I was trying to retrace my...

Delphi - Use a string variable's name in assignfile()

Is it possible to use a variable in the assignfile command? Eg. f : Textfile ; sFile : string ; {contains 'MyFile.txt' as content} ... cFileDir = 'C:\Users\User\Desktop\Data Engine\Data\Country' ; ... Assignfile(f, cFileDir + '\' + sFile) ; ... I appreciate your help very much. if it's unclear I'll edit...

Set node state in a virtual tree

I have created a virtual tree with multiple node and I want to disable some of them. I've seen there's a States property of a node. Which is a property of a type TVirtualNodeStates so I've check what kind of states I can set and apparently TVirtualNodeStates is a set...

Get which capture group matched a result using Delphi's TRegex

I've written a regex whose job is to return all matches to its three alternative capture groups. My goal is to learn which capture group produced each match. PCRE seems able to produce that information. But I haven't yet been able coerce the TRegEx class in Delphi XE8 to yield...

Can I specify the save location for Delphi .dsk file?

I want the Delphi IDE to remember which files I had open, etc., but if I enable the "Project Desktop" autosave option (Tools -> Options -> EnvironmentOptions in XE7) it puts the .dsk file in the root folder of my source code. We are using git for our version control,...

Expression illegal in evaluator

I'm trying to code something but there is happening something I don't understand. I get some values from a database and loop over them and change some of them if needed. This is what I'm trying to do: if qryGeneral.fieldbyname('B_PRIJS').IsNull or qryGeneral.fieldbyname('B_PRIJS').Value = 0 then begin if (qryGeneral.fieldbyname('V_PRIJS').Value <> 0)...

SetProcessWorkingSetSize does not work in compiling 64bit

I use the following command to reduce the memory usage of my program, I'm actually testing it, only when I compile the program in 64bit this command does not work fot, no error occurs, only the memory in task managerIt does not decrease too, since in compiling 32bit works perfectly,...

What is required in Delphi 2007 to use Variant arrays?

I'm a newbie in Delphi, using Delphi 2007. I am learning things related to COM programming, in order to make a basic plugin to a program called Retail Pro. I have a little of background in .NET (C#, ASP), NetBeans (Java, JSF) and PHP. Anyway, I'm following this intro tutorial...

Is there any Delphi implementation of MurMurHash3?

Is there any Delphi implementation of MurMurHash 3? I tried implementing it myself, but my implementation is actually slower that the MurMurHash2. Is it normal? Is there any other implementation? This is mine: function MurMur3_32(const S: AnsiString; const Seed: LongWord=$9747b28c): LongWord; const c1 = $cc9e2d51; c2 = $1b873593; r1 =...

Open file manage and get selected file

Using Delphi XE 8 and building Android app, can I browse files in the device by opening a certain file manager app installed on the device and then get back that selected file name and path ?

Delphi XE8: problems running an external console application, waiting for its results and capturing its results

In Delphi XE8 under Windows, I am trying to call an external console application and capture its output. I use the following code, as described in Capture the output from a DOS (command/console) Window and also Getting output from a shell/dos app into a Delphi app: procedure TForm1.Button1Click(Sender: TObject) ;...

How to make my custom control be notified when his form or application receives and loses focus?

I want my control to receive distinct notifications only when it's parent form (not panel or something else, just the main form of this control) receives and loses focus. Doesn't matter if the focus is switched from another form of the application or between my application and other application, it...

Digital Metaphors Report Builder Surround Group Inside Box

I'm interested in creating a report that contains a group in it. I'd like the group to be enclosed in a box where the box surrounds the group in every page I've tried this using lines and placing them in such a way that there is one on the group...

Why does my application using OmniThreadLibrary Parallel.Pipeline continue remain running in the background after being closed?

I'm using OmniThreadLibrary to implement a background pipleline for sending emails (refer to this SO question). I notice that after closing the application, it continues running in the background (seen in Windows Task Manager). That means that there is something wrong in my code in the way I implemented the...

'Session Ended' when lauching app from Delphi to iOS Simulator

I'm trying to deploy a multi-platform application (written in Delphi XE7 + Firemonkey) to iOS Simulator, through these parameters: Delphi XE7 OSX 10.8 Mountain Lion XCode 5.1.1 Command Line Tools PAServer 15.0 (iOS SDK 7.1 - also tested with 6.1) My Application needs to work in Windows, Android, iOS and...

Asynchronous TADOQuery's OnFetchComplete not synchonized to main thread

When using TADOQuery with [eoAsyncFetchNonBlocking] and attaching to OnFetchComplete event I found that OnFetchComplete is not executing in the main thread (tested in XE4 and XE8). I assume this a bug*, since most of us will do work in the UI on these type of event. I believe this to...

Delphi - extract string between tags (duplicate tags)

I'm trying to write a function to extract a string between two tags. The problem is that the first tag is a duplicate in that string with an unknown count e.g. Str := 'Delphi App Hello Hello SomeText here Hello Hello Hello This is a Test!'; What i want exactly...

how to connect to a NIC card or network adapter knowing its IP address?

Say I have two NIC or adapter card on my system and also I found their IP address through the following code: procedure TForm4.RetrieveLocalAdapterInformation(strings: Tmemo); var pAdapterInfo, pTempAdapterInfo: PIP_ADAPTER_INFO; AdapterInfo: IP_ADAPTER_INFO; BufLen: DWORD; Status: DWORD; strMAC: String; i: Integer; begin strings.Clear; BufLen:= sizeof(AdapterInfo); pAdapterInfo:= @AdapterInfo; Status:= GetAdaptersInfo(nil, BufLen); pAdapterInfo:= AllocMem(BufLen);...

Delphi XE4 - TImage is not displayed at runtime

Note: In the original question I was in a hurry and wrongly assumed that the problem was related to VCL Styles, but at the end after some testing it seems to be related to the SynGdiPlus.pas, so I removed the original description. The problem: TImage correctly shows the image at...

Preventing component creation - Delphi

I am creating an application which makes use of several TTabsheets (from the TPageControl component). Is it possible to prevent a component (in this case a tab) from being created during the program startup? I want to manually create the tabs at a later stage. This is not a dynamic...