Results 1 to 4 of 4

Thread: (Resolved) Rename Files while working with them

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354

    (Resolved) Rename Files while working with them

    I am trying to change the file names of all the files in a directory based on content of the file. So I am opening the file, reading the content, storing the new file name in a variable and then trying to change the name of the file.

    This is not working because when I start this loop I am opening the file and viewing it so it won't allow me to change while the file is in use. Should I store the old and new file names in an array and do the renames after the For Next Loop is complete?

    VB Code:
    1. '
    2.     Private Sub btnChange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChange.Click
    3.         Dim dir As New DirectoryInfo("C:\KVCpdfs\")
    4.         Dim strFileName As String = Nothing
    5.         Dim strNewName As String = Nothing
    6.         For Each file As FileInfo In dir.GetFiles()
    7.  
    8.             strNewName = ReadFile(file.FullName).ToString & ".pdf"
    9.             My.Computer.FileSystem.RenameFile(file.FullName, strNewName)
    10.  
    11.         Next
    12.     End Sub
    Last edited by BukHix; Sep 27th, 2009 at 09:59 PM. Reason: Resolved

  2. #2

    Re: Rename Files while working with them (problem)

    You called ReadFile() But you never 'closed' the file, so it is still in use in memory. You must close the file to rename it, or you will get an error.

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

    Re: Rename Files while working with them (problem)

    There's a much simpler way:
    vb.net Code:
    1. For Each filePath As String In IO.Directory.GetFiles("C:\KVCCpdfs")
    2.     IO.File.Move(filePath, IO.Path.ChangeExtension(filePath, ".pdf"))
    3. Next
    The My namespace has equivalents to File.Move (which you've already used) and Path.ChangeExtension but they don't actually offer any advantage and they are longer to type so I stick with the System.IO namespace. There's no harm in using those My methods though.
    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

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354

    Re: Rename Files while working with them (problem)

    That was the issue. Thanks!

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