help renaming file

D

djcamo

Hi, I'm hoping some one can help with some coding issues I'm having.
Below is some code I use to rename a file if it already exists in a
folder. As you can see I have 5 nested if loops which means that the
file can only be renamed 5 times. What I am having trouble with is a
recursive loop that allows an infinite amount of this file being
renamed. Hopes this make sense.

If newfi.Exists Then
newfilename = surname & "_1" & "_" & etick & ".txt"
Dim newfi1 As New FileInfo(agPath + newfilename)
If newfi1.Exists Then
newfilename = surname & "_2" & "_" & etick &
".txt"
Dim newfi2 As New FileInfo(agPath + newfilename)
If newfi2.Exists Then
newfilename = surname & "_3" & "_" & etick &
".txt"
Dim newfi3 As New FileInfo(agPath +
newfilename)
If newfi3.Exists Then
newfilename = surname & "_4" & "_" & etick
& ".txt"
If newfi3.Exists Then
Dim msg As String = "Unable to save
coupon " & surname & " again" & vbCr & "please delete existing record
first"
MsgBox(msg, MsgBoxStyle.Critical,
"Warning")
flag = True
Exit Sub
End If
End If
End If
End If
Else
newfilename = surname & "_" & etick & ".txt"
End If

Cheers
Dave
 
S

SurturZ

This code will do what you want:

Function CreateFile(ByVal agPath As String, ByVal surname As String,
ByVal etick As String) As String
Dim strFilename As String = ""
Dim i As Integer = 1
Do
strFilename = surname & "_" & i.ToString & "_" & etick & ".txt"
Dim fnfNew As New FileInfo(agPath & strFilename)
If Not fnfNew.Exists Then
Exit Do
End If
i += 1
Loop
Return strFilename
End Function

However, it has two problems:
1) You really should limit the number of retries as you could end up hanging
the system
2) You really need to create the file as part of checking if the same
program will be run multiple times simultaneously.
 
D

djcamo

This code will do what you want:

    Function CreateFile(ByVal agPath As String, ByVal surname As String,
ByVal etick As String) As String
        Dim strFilename As String = ""
        Dim i As Integer = 1
        Do
            strFilename = surname & "_" & i.ToString & "_" & etick & ".txt"
            Dim fnfNew As New FileInfo(agPath & strFilename)
            If Not fnfNew.Exists Then
                Exit Do
            End If
            i += 1
        Loop
        Return strFilename
    End Function

However, it has two problems:
1) You really should limit the number of retries as you could end up hanging
the system
2) You really need to create the file as part of checking if the same
program will be run multiple times simultaneously.

--
David Streeter
Synchrotech Software
Sydney Australia







- Show quoted text -

thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top