Home All Groups Group Topic Archive Search About

Getting the Parent firectory of a file

Author
13 May 2006 12:05 AM
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.

Author
13 May 2006 1:10 AM
jayeldee
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
Author
13 May 2006 2:22 AM
Paulers
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
Author
13 May 2006 3:32 AM
jayeldee
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.
Author
13 May 2006 7:34 PM
Herfried K. Wagner [MVP]
"Paulers" <SuperG***@gmail.com> schrieb:
> how do I get the file's parent directory name out of a path like this?

Check out the shared methods of 'System.IO.Path'.

--
M S   Herfried K. Wagner
M V P  <URL:http://dotnet.mvps.org/>
V B   <URL:http://classicvb.org/petition/>