Getting the Parent firectory of a file

  • Thread starter Thread starter Paulers
  • Start date Start date
P

Paulers

hello.

how do I get the file's parent directory name out of a path like this?

c:\test\myDirectory\file.txt

Im looking to extract the "Directory" from the path so I can create
myDirectory in another directory and copy the files.

what I am really trying to accomplish is to move the parent directory
and all it's files to another directory but I can not get a
Directory.Move to work so I am attempting to do it manually.


any help is greatly appreciated.
 
Here's a couple of functions you can use.

I'm curious - why couldn't you get the Directory.Move to work? Did it
give you an error? Docs say 'The destination cannot be another disk
volume or a directory with the identical name. It can be an existing
directory to which you want to add this directory as a subdirectory.'

Private Function GetDirectory(ByVal FileName As String) As String

Dim fi As IO.FileInfo

fi = New IO.FileInfo(FileName)

Return fi.Directory.FullName

End Function

Private Sub CopyDirs(ByVal sourceDir As String, ByVal targetDir As
String, ByVal OverwriteFiles As Boolean)

Dim sourceDirInfo As IO.DirectoryInfo
Dim filesToCopy() As IO.FileInfo

' check that the source dir exists
If Not IO.Directory.Exists(sourceDir) Then
Throw New IO.DirectoryNotFoundException("Invalid sourceDir:
" & sourceDir)
Else
sourceDirInfo = New IO.DirectoryInfo(sourceDir)
filesToCopy = sourceDirInfo.GetFiles
End If

' Create the target directory if it doesn't exist
If Not IO.Directory.Exists(targetDir) Then
IO.Directory.CreateDirectory(targetDir)
End If

' loop through the files and copy them
For Each f As IO.FileInfo In filesToCopy
f.CopyTo(targetDir & "\" & f.Name, OverwriteFiles)
Next

Return

End Sub
 
Wow thanks a bunch for all your help!

how do I pull the 2222 out of c:\1111\2222 ?

Im trying to construct the destination variable
 
If you create a new IO.FileInfo and pass it "c:\1111\2222" in the
constructor, you can get the name of the file and the name of its
directory with the the .Name and .Directory.FullName properties.
 
Back
Top