Folder or file?

  • Thread starter Thread starter Able
  • Start date Start date
A

Able

Dear friends

A string is either a foldername or a name of a single file. Do somebody know
a proper way to qualify whether the string is the one or the another?

Regards Able
 
use the FileAttributes to retrieve the attributes of the fileinfo object
which you can then check for the FileAttributes.Directory flag to determine
whether its a file or directory. However, note that if you provide something
like "C:\FileDoesNotExist.txt" and the file you specified does not exist,
it'll still return a FileInfo object but with the Directory Attribute set.
here's a small example of how you would do this:

Private Sub TestFileOrDirectory(byVal sFileOrDir as String)
Dim oFileInfo As FileInfo = New FileInfo(sFileOrDir)
If Not oFileInfo Is Nothing Then
If (oFileInfo.Attributes And FileAttributes.Directory) = 0 Then
MsgBox("Its a file!")
Else
MsgBox("Its a directory!")
End If
End If
End Sub

hope this helps..
Imran.
 
I don't think it would be so simple of a test without inspecting the actual
file or folder itself. Files may or may not have extensions.

Dim path As String = "c:\test"
Dim s As String = System.IO.Path.GetDirectoryName(path)

If s = Nothing Then
MsgBox("root folder")
ElseIf s <> path Then
MsgBox("could be file or folder with no extension")
If System.IO.Directory.Exists(path) Then
MsgBox("folder")
ElseIf System.IO.File.Exists(path) Then
MsgBox("file")
Else
MsgBox("doesn't exists")
End If
Else
MsgBox("file")
End If

Greg
 
Without knowing how you're obtaining the string, I can only speculate that
you're getting it without having any knowledge of what it represents, or
using a UI dialog or other means of enforcing the name having a trailing
backslash to denote a directory. You could try this:

Imports System
Imports System.IO

Function IsDirectoryName(ByVal TheString As String) As Boolean
Dim ADirectory As New DirectoryInfo(TheString)
If ADirectory.Exists Then
Return True
Else
Return False
End If
End Function

(meanwhile, back at the ranch...)
' TheStringToCheck must be a fully-qualified drive:\path\maybe_a_filename
If IsDirectoryName(TheStringToCheck) Then
' we have a directory
Else
' this is a file
End If
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top