Android Code Snippet [B4X] Automatically increment file names

Discussion in 'Code Snippets' started by Alexander Stolte, Jul 17, 2018.

  1. Alexander Stolte

    Alexander Stolte Well-Known Member Licensed User

    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.

    Code:
    checkfilename(File.DirDefaultExternal,"mytestname.jpg",0,"mytestname.jpg")
    Code:
    Sub checkfilename(dir As String,filename As String, lastint As Int,lastfilename As StringAs String
      
        
    Dim filename2(2As 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
     
    fredo likes this.
  2. Knoppi

    Knoppi Active Member Licensed User

    My version of "Automatically increment file names"

    Code:
    Sub getIncrementFileName( Dir As String, FileName As StringAs 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
    Code:
    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
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice