Android Code Snippet [B4X] Automatically increment file names

Hey,

if you download a file with Google Chrome for example and you have you've already downloaded this one time, then a number will appear next to it. This is now easy possible with this peace of code.

B4X:
checkfilename(File.DirDefaultExternal,"mytestname.jpg",0,"mytestname.jpg")

B4X:
Sub checkfilename(dir As String,filename As String, lastint As Int,lastfilename As String) As String
  
    Dim filename2(2) As String  = Regex.Split("\.",filename)
    Dim filename3 As String = filename
    If File.Exists(dir,lastfilename) = True Then
        lastint = lastint +1
              
        lastfilename = filename2(0) & "(" & lastint  & ")" & "." & filename2(1)
      
        checkfilename(dir,filename3,lastint,lastfilename)
      
    Else
                      
        Return lastfilename
      
    End If
  
End Sub

Output: mytestname(1).jpg

Greetings
 

Knoppi

Active Member
Licensed User
Longtime User
My version of "Automatically increment file names"

B4X:
Sub getIncrementFileName( Dir As String, FileName As String) As String
    Dim Base As String = FileName.SubString2( 0, FileName.LastIndexOf( "."))
    Dim Ext  As String = FileName.SubString( FileName.LastIndexOf( "."))
    
    Dim newFile As String = FileName
    Dim count As Int = 1
    Do While File.Exists( Dir, newFile) = True
        newFile = $"${Base}(${count})${Ext}"$
        count = count +1
    Loop
    Return newFile
End Sub
B4X:
Sub Test_Increment
   Dim Dir As String = File.DirTemp
   Dim FileName As String = "passwd.dat"
   For i=0 To 10
        Dim newName As String = getIncrementFileName( Dir, FileName)
        Log( i &TAB& newName)
        File.WriteString( Dir, newName, "File = "& i)
    Next
End Sub
0 passwd.dat
1 passwd(1).dat
2 passwd(2).dat
3 passwd(3).dat
4 passwd(4).dat
5 passwd(5).dat
6 passwd(6).dat
7 passwd(7).dat
8 passwd(8).dat
9 passwd(9).dat
10 passwd(10).dat
 
Top