Results 1 to 12 of 12

Thread: [RESOLVED] Adding characters to file name to prevent overwriting?

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2012
    Posts
    14

    Resolved [RESOLVED] Adding characters to file name to prevent overwriting?

    Hi, I'm making a small application where the user inputs some files in a listbox, and then the files are converted and saved in a folder. However, I still don't know how to make it see if there are files with the same name inside the listbox. So, for example if there are two files called "FileX", it will convert each one and save them, but the last converted one will replace the first one. Also, it will replace any file in that folder with the same name.

    I want my application to see if there are files with the same name in that folder, and if there are, add a "(1)" to the last converted file, and if there's already a file with "(1)" in its name, add 1, so it would be a "(2)", "(3)" and so on.

    My code is this:

    Code:
      
    Dim W As IO.StreamWriter
    Dim i As Integer
            
            W = New IO.StreamWriter("C:\Myprogram\Converting.bat")
    
    For i = 0 To listbox1.Items.Count - 1
    
                Dim getname As String
                getname = System.IO.Path.GetFileName(listbox1.Items.Item(i))
              
                'I think the code should be here
    
                W.WriteLine(*options* & System.IO.Path.GetFileNameWithoutExtension(listbox1.Items.Item(i)) & ".converted" '& some code in here?)
            Next
    
            W.Close()
    Sorry if I don't provide much code, I'm still learning.

    Any help would be appreciated.
    Thanks in advance.

  2. #2
    Hyperactive Member
    Join Date
    Jan 2010
    Posts
    259

    Re: Adding characters to file name to prevent overwriting?

    Time for you to look into recursion.

    Code:
    Public Function CheckAndGenerateUniqueCopyName(path As String, Optional seed As Integer = 1) As String
            'Check if the supplied path exists
            If System.IO.File.Exists(path) Then
    
               'The path exists so lets append the seed to the end of it
                path &= "(" & seed & ")"
    
                'Increment the seed value for the next iteration
                seed += 1
                
                'Call the same method with the new parameters until a result is found
                path = CheckAndGenerateUniqueCopyName(path, seed, False)
            End If
    
            Return path
        End Function
    The above code has not been checked, but that is, in general, what you want to do.
    Last edited by wakawaka; Jan 16th, 2013 at 05:30 PM.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding characters to file name to prevent overwriting?

    Recursion is not necessarily bad but, in this case, iteration seems more appropriate, e.g.
    Code:
    Private Function GetUniqueNumberedFilePath(filePath As String) As String
        If File.Exists(filePath) Then
            Dim folderPath = Path.GetDirectoryName(filePath)
            Dim fileName = Path.GetFileNameWithoutExtension(filePath)
            Dim extension = Path.GetExtension(filePath)
            Dim fileNumber = 1
    
            Do
                filePath = Path.Combine(folderPath,
                                        String.Format("{0} ({1}){2}",
                                                      fileName,
                                                      fileNumber,
                                                      extension))
                fileNumber += 1
            Loop While File.Exists(filePath)
        End If
    
        Return filePath
    End Function
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Adding characters to file name to prevent overwriting?

    An alternative to jmcilhinney's solution getting an array of files matching the file name and extension and checking against that rather than hitting the file system each time to check if a file exists.

    vb.net Code:
    1. Private Function GetUniqueFileName(filePath As String) As String
    2.         Dim folderName = Path.GetDirectoryName(filePath)
    3.         Dim fileName = Path.GetFileNameWithoutExtension(filePath)
    4.         Dim extension = Path.GetExtension(filePath)
    5.  
    6.         Dim fileNames = Directory.GetFiles(folderName, fileName & "*" & extension)
    7.         Dim fileNumber = 1
    8.  
    9.         If fileNames.Contains(filePath) Then
    10.             Do
    11.                 filePath = Path.Combine(folderName, String.Format("{0} ({1}){2}",
    12.                                                                   fileName,
    13.                                                                   fileNumber,
    14.                                                                   extension))
    15.                 fileNumber += 1
    16.             Loop While fileNames.Contains(filePath)
    17.         End If
    18.  
    19.         Return filePath
    20.     End Function
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding characters to file name to prevent overwriting?

    Quote Originally Posted by MattP View Post
    An alternative to jmcilhinney's solution getting an array of files matching the file name and extension and checking against that rather than hitting the file system each time to check if a file exists.

    vb.net Code:
    1. Private Function GetUniqueFileName(filePath As String) As String
    2.         Dim folderName = Path.GetDirectoryName(filePath)
    3.         Dim fileName = Path.GetFileNameWithoutExtension(filePath)
    4.         Dim extension = Path.GetExtension(filePath)
    5.  
    6.         Dim fileNames = Directory.GetFiles(folderName, fileName & "*" & extension)
    7.         Dim fileNumber = 1
    8.  
    9.         If fileNames.Contains(filePath) Then
    10.             Do
    11.                 filePath = Path.Combine(folderName, String.Format("{0} ({1}){2}",
    12.                                                                   fileName,
    13.                                                                   fileNumber,
    14.                                                                   extension))
    15.                 fileNumber += 1
    16.             Loop While fileNames.Contains(filePath)
    17.         End If
    18.  
    19.         Return filePath
    20.     End Function
    While it's not really a big deal, only one of those five declared variables is used unless you enter the If block so the other four really belong inside the If block too.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  6. #6
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Adding characters to file name to prevent overwriting?

    Quote Originally Posted by jmcilhinney View Post
    While it's not really a big deal, only one of those five declared variables is used unless you enter the If block so the other four really belong inside the If block too.
    Huh? I agree that the fileNumber variable should be scoped to within the If block but the others have to be outside of it.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  7. #7
    Hyperactive Member
    Join Date
    Jan 2010
    Posts
    259

    Re: Adding characters to file name to prevent overwriting?

    Quote Originally Posted by jmcilhinney View Post
    Recursion is not necessarily bad but, in this case, iteration seems more appropriate, e.g.
    Code:
    Private Function GetUniqueNumberedFilePath(filePath As String) As String
        If File.Exists(filePath) Then
            Dim folderPath = Path.GetDirectoryName(filePath)
            Dim fileName = Path.GetFileNameWithoutExtension(filePath)
            Dim extension = Path.GetExtension(filePath)
            Dim fileNumber = 1
    
            Do
                filePath = Path.Combine(folderPath,
                                        String.Format("{0} ({1}){2}",
                                                      fileName,
                                                      fileNumber,
                                                      extension))
                fileNumber += 1
            Loop While File.Exists(filePath)
        End If
    
        Return filePath
    End Function
    Damn you and your better solutions, I'll never get any rep with you on this forums!!!!

  8. #8

    Thread Starter
    New Member
    Join Date
    Sep 2012
    Posts
    14

    Re: Adding characters to file name to prevent overwriting?

    Quote Originally Posted by wakawaka View Post
    Time for you to look into recursion.

    Code:
    Public Function CheckAndGenerateUniqueCopyName(path As String, Optional seed As Integer = 1) As String
            'Check if the supplied path exists
            If System.IO.File.Exists(path) Then
    
               'The path exists so lets append the seed to the end of it
                path &= "(" & seed & ")"
    
                'Increment the seed value for the next iteration
                seed += 1
                
                'Call the same method with the new parameters until a result is found
                path = CheckAndGenerateUniqueCopyName(path, seed, False)
            End If
    
            Return path
        End Function
    The above code has not been checked, but that is, in general, what you want to do.
    Just a little question, why am I getting the following error
    Code:
    Too many arguments foro ‘Public Function CheckAndGenerateUniqueCopyName(path As String, [seed As String, [seed As Integer=1]) As String’.
    Also, I'm not very sure of how do i have to add the function to the StreamWriter.

    Thanks a lot.
    Last edited by Guado; Jan 17th, 2013 at 11:59 AM.

  9. #9
    Hyperactive Member
    Join Date
    Jan 2010
    Posts
    259

    Re: Adding characters to file name to prevent overwriting?

    You add the method into your code inside of a class and call it like so:

    Code:
    Dim uniquePath As String = CheckAndGenerateUniqueCopyName("C:\temp\myfile.txt")
    'or like so if you want to start with a different seed value
    Dim uniquePath As String = CheckAndGenerateUniqueCopyName("C:\temp\myfile.txt", 20)
    'Assuming the path exists it will return a file path of "C:\temp\myfile.txt(20)"
    I should mention mine is simple. jml's example is a different way to accomplish it but his also formats the path so the instead of my "myfile.txt(20)", his returns "myfile (20).txt".

  10. #10
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Adding characters to file name to prevent overwriting?

    Quote Originally Posted by wakawaka View Post
    jml's example is a different way to accomplish it but his also formats the path so the instead of my "myfile.txt(20)", his returns "myfile (20).txt".
    myfile.txt(20) is not a good format for an output file. myfile(20).txt will open up with whatever editor is associated with txt files. You'll get a dialog asking which program to open .txt(20) files which is bad UX.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  11. #11
    Hyperactive Member
    Join Date
    Jan 2010
    Posts
    259

    Re: Adding characters to file name to prevent overwriting?

    That is why I made the comment, but if the file is being read by an application and not a person, it is perfectly fine to do it as such.

  12. #12

    Thread Starter
    New Member
    Join Date
    Sep 2012
    Posts
    14

    Re: Adding characters to file name to prevent overwriting?

    Although I still don't understand how this code works I'll try to add it to my code, but I think I have to learn to use functions better.

    Thanks a lot, you're very helpful.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width