VB.NET - Check if URL is a directory or file - vb.net

Is there a way, in VB.NET, to check if a URL is a directory? I've seen a lot of methods of checking if a local path is a directory but what about a remote url (i.e. http://website.com/foo) I read that some plain text files have no extension so I need a solution other than checking what if the file name contains a space or something.

You can use FileAttributes class:
'get the file attributes for file or directory
FileAttributes attr = File.GetAttributes("c:\\Temp")
'detect whether its a directory or file
If ((attr & FileAttributes.Directory) = FileAttributes.Directory) Then
MessageBox.Show("Its a directory")
Else
MessageBox.Show("Its a file")
End IF
Or you can use the Uri class:
Private IsLocalPath(Byval p As String) As Boolean
Return New Uri(p).IsFile
End Function
You can enhance this method to include support for certain invalid URIs:
Private IsLocalPath(Byval p As String) As Boolean
If (p.StartsWith("http:\\")) Then
Return False
End IF
Return New Uri(p).IsFile
End Function

The only solution I can think of is to try to download the file from the Internet, if the download succeeded So it is a file, otherwise it is not a file (but you don't know for sure that this is a directory).

This worked for me...
If System.IO.Path.HasExtension(FileAddress.Text) Then
MessageBox.Show("Its a file")
Else
MessageBox.Show("Its a directory")
End IF

Related

visualbasic cant delete .zip file in a directory

i have three folder in "D:\TestField". These are "backups","ExampleFileUpdatePrimary","ExampleFileUpdateSecondary.zip". I can delete "D:\TestField\ExampleFileUpdatePrimary" folder ,but i cant delete "D:\TestField\ExampleFileUpdateSecondary.zip"
my sub function is ;
Private Sub DeleteFolder(ByVal path As String)
path = path.Remove(path.Length - 1) 'D:\TestField\ExampleFileUpdatePrimary
Dim path2 = path & ".zip" 'D:\TestField\ExampleFileUpdateSecondary.zip
My.Computer.FileSystem.DeleteDirectory(path, FileIO.DeleteDirectoryOption.DeleteAllContents) 'its working
'Dim di = New IO.DirectoryInfo(path2) 'try1
'di.Delete(True)
'IO.Directory.Delete(path2) 'try2
'My.Computer.FileSystem.DeleteDirectory(path2, FileIO.DeleteDirectoryOption.DeleteAllContents) 'try3
End Sub
try1,try2 exceptions says " The directory name is invalid"
try3 exception says "System.IO.DirectoryNotFoundException: ''D:\TestField\ExampleFileUpdateSecondary.zip "
i couldnot find a new solution or try to delete a .zip file in code
thanks
Directory entries ending on .zip are usually files not folders, even though Windows Explorer displays them as folders.
Since they are files, use File.Delete instead.

Delete items within a folder rather than deleing the entire folder itself using vb.net

I want to delete all the files contained in a folder. The below code does delete the file but also deletes the folder itself. I am aware you will need to perform a for loop to remove each item from the folder, but can't find the information on how to start the code for it. Can someone point me in the correct direction.
Dim folderFiles() As String
folderFiles= Directory.GetFileSystemEntries("C:\New Folder")
For Each element As String In files
If (Not Directory.Exists(folder)) Then
File.Delete(Path.Combine("C:\New Folder", Path.GetFileName(folder)))
End If
Next
This is the easier way :
For Each the_file As String In Directory.GetFileSystemEntries("C:\New folder")
File.Delete(the_file)
Next
Don't bother to grab the list of files and then browse it, use your loop directly on it.
I have a function for that. With it, you can also delete all files of a pattern even for all subdirectories:
Public Sub DeleteFiles(Path As String,
Optional Pattern As String = "*.*",
Optional All As Boolean = False)
Dim SO As IO.SearchOption = If(All, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly)
For Each Filename As String In Directory.GetFiles(Path, Pattern, SO)
File.Delete(Filename)
Next
End Sub
So you could use it for your task like:
DeleteFiles("C:\New Folder")
I would use this code
For Each file As String In IO.Directory.GetFiles("the path")
IO.File.Delete(file)
Next
This deletes everything in the folder but not the folder itself.
This is quick and easy, especially if 1) there's nothing special about the folder, eg permissions, and 2) the folder might contain sub-folders, sub-sub-folders, etc.
Simply delete the original folder and recreate it:
Dim path As String = {your path}
IO.Directory.Delete(path, recursive:=True)
IO.Directory.CreateDirectory(path)
Another option for folders with sub-folders where you wish to keep the (empty) sub-folders, is to use recursion:
Sub EmptyFolder(path As String) As Boolean
Try
For Each dir As String In IO.Directory.GetDirectories(path)
EmptyFolder(dir)
Next dir
For Each file As String In IO.Directory.GetFiles(path)
IO.File.Delete(file)
Next file
Catch
Throw
End Try
End Function

Saving image from php id URL using webbrowser in VB.net

I am trying to save a image from webbrowser but can't find an answer for it.
Example of the problem is the URL is hxxp://domain[.]com/image/?img=1234 on webbrowser it shows the image and the source is <img src='hxxp://domain[.]com/image/?img=1234'>..
I was unable to save it using the My.Computer.Network.DownloadFile and MemoryStream(tClient.DownloadData methods.
In order to download the file, I will need to session cookie also?
How can I do this?
Any image that you see in the WebBrowser has already been downloaded to your computer. It is normally cached in the folder:
C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files
or whatever other folder is set in Internet Options. You can get your image from that folder.
The following program shows how to copy file TDAssurance_Col.png from the Temporary Internet Files folder to the C:\Temp folder.
Module Module1
Sub Main()
CopyFileFromTemporaryInternetFolder("TDAssurance_Col.png", "C:\Temp")
End Sub
Public Sub CopyFileFromTemporaryInternetFolder(filename As String, destinationFolder As String)
' Search actual path of filename.
Dim temporaryInternetFilesFolder As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), "Content.IE5")
Dim pattern As String = Path.GetFileNameWithoutExtension(filename) & "*" & Path.GetExtension(filename)
Dim pathnames() As String = Directory.GetFiles(temporaryInternetFilesFolder, pattern, SearchOption.AllDirectories)
' If file found, copy it.
If pathnames.Count > 0 Then
File.Copy(pathnames(0), Path.Combine(destinationFolder, filename))
End If
End Sub
End Module

Access vba Check if file exists

I have a database split in FrontEnd and BackEnd.
I have it running:
i) in my office
ii) updating/testing in my personal computer.
My BackEnd file is running in different Folder location according to computer running.
I want to place a code and check if file exist.
Code:
Sub FileExists()
Dim strPath As String '<== Office.
Dim strApplicationFolder As String
Dim strPathAdmin As String '<== Admin.
strPath = "\\iMac\Temp\"
strApplicationFolder = Application.CurrentProject.Path
strPathAdmin = strApplicationFolder & "\Temp\"
If Dir(strApplicationFolder & "SerialKey.txt") = "" Then
'===> Admin User.
If Dir(strPathAdmin & "*.*") = "" Then
'===> Empty Folder.
Else
'===> Files on folder.
End If
Else
'===> Office User.
If Dir(strPath & "*.*") = "" Then
'===> Empty Folder.
Else
'===> Files on folder.
End If
End If
End Sub()
I have this until now.
Any help.
Thank you...
Create a small function to check if a file exists and call it when needed.
Public Function FileExists(ByVal path_ As String) As Boolean
FileExists = (Len(Dir(path_)) > 0)
End Function
Since the backend database paths dont change, why dont you declare two constants and simply check their value?
Sub Exist()
Const workFolder As String = "C:\Work Folder\backend.accdb"
Const personalFolder As String = "D:\Personal Folder\backend.accdb"
If FileExists(workFolder) Then
'Work folder exists
End If
'....
If FileExists(personalFolder) Then
'Personal folder exists
End If
End Sub
This is a very belated reply, but don't reinvent the wheel. VBA can access the FileSystemObject, which includes a powerful set of methods that fetch file and folder information without requiring you to write your own functions, and the resulting code is much easier to read.
Second, borrowing on the previous answer, you know the folders you want the code to look at, and they don't change much, but because they could, I would also move your parameters into the declaration so they can be customized if needed or default to existing values.
Finally, FileExists is a verb, which should scream Function rather than Sub, so I'm guessing you want to return something and use it elsewhere in higher level code. It so happens that FileExists is already the name of a method in FileSystemObject, so I'm going to rename your function to LocatePath. You could return the valid path of the file you're looking for and decide by convention to quietly return an empty string "" if the target isn't found, and handle that in the calling procedure.
fs.BuildPath(strRootPath, strFileOrSubDir) appends strFileOrSubDir to strRootPath to construct a properly
formatted, full pathname and you don't need to worry about
whether you have backslashes (or too many) between the two.
It can be used to append files, or subdirectories, or
files in subdirectories.
fs.FileExists(strFullPath) is simple, returns True if strFullPath exists,
and False otherwise.
fs.GetFolder(strFolderName) returns a Folder object that has a
.Files property, which is a Collection object. Collection
objects in turn have a .Count property, which in this example
indicates how many files are in strFolderName. The Collection
object could also be used to iterate over all the files in the
folder individually.
What follows is your code refactored to incorporate all the changes I recommend according to what I think you're trying to achieve. It's not as symmetric as I'd like, but mirrors your code, and it's simple, easy to read, and finished in the sense that it does something.
Function LocatePath(Optional strWorkPath as String = "\\iMac",
Optional strHomePath as String = CurrentProject.Path,
Optional strFile as String = "SerialKey.txt"
Optional strSubDir as String = "Temp") as String
Dim fs as Object
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FileExists(fs.BuildPath(strHomePath, strFile)) Then
If fs.GetFolder(fs.BuildPath(strHomePath, strSubDir).Files.Count > 0 Then '===> Admin User.
LocatePath = fs.BuildPath(strHomePath, strFile)
ElseIf fs.GetFolder(fs.BuildPath(strWorkPath, strSubDir).Files.Count > 0 Then '===> Office User
LocatePath = fs.BuildPath(strWorkPath, strFile)
End If
Else 'Target conditions not found
LocatePath = ""
End If
Set fs = Nothing
End Function()
Ideally, I probably wouldn't specify strHomePath as String = CurrentProject.Path because strWorkPath as String = CurrentProject.Path is probably also true when you're at work, and you would want to do a better job of differentiating between the two environments. This is also what causes the little problem with symmetry that I mentioned.

Identifying if a JPG file is open

I've been trying to set an error trap that will detect if a file is already open. This is no problem when the file is a text file using the following code:
Private Function FILEOPEN(ByVal sFile As String) As Boolean
Dim THISFILEOPEN As Boolean = False
Try
Using f As New IO.FileStream(sFile, IO.FileMode.Open)
THISFILEOPEN = False
End Using
Catch
THISFILEOPEN = True
End Try
Return THISFILEOPEN
End Function
My problem is that when the file is an open JPG file, not a text file, the above function returns False indicating that it is not open? I have tried different variations of the function but still cannot find a function that can tell if a JPG file is open.
You should NOT do this kind of behavior. Simple answer is because after you check, but before you do anything with it, the file may become unavailable. A proper way is to handle an exception as you access the file. You may find this answer helpful:
https://stackoverflow.com/a/11288781/897326