|
-
Sep 27th, 2009, 09:39 PM
#1
Thread Starter
Hyperactive Member
(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:
'
Private Sub btnChange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChange.Click
Dim dir As New DirectoryInfo("C:\KVCpdfs\")
Dim strFileName As String = Nothing
Dim strNewName As String = Nothing
For Each file As FileInfo In dir.GetFiles()
strNewName = ReadFile(file.FullName).ToString & ".pdf"
My.Computer.FileSystem.RenameFile(file.FullName, strNewName)
Next
End Sub
Last edited by BukHix; Sep 27th, 2009 at 09:59 PM.
Reason: Resolved
-
Sep 27th, 2009, 09:41 PM
#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.
-
Sep 27th, 2009, 09:53 PM
#3
Re: Rename Files while working with them (problem)
There's a much simpler way:
vb.net Code:
For Each filePath As String In IO.Directory.GetFiles("C:\KVCCpdfs") IO.File.Move(filePath, IO.Path.ChangeExtension(filePath, ".pdf")) 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.
-
Sep 27th, 2009, 09:57 PM
#4
Thread Starter
Hyperactive Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|