Phasing website directory/ folder name vb.net - vb.net

I have a website with folders i want vb.net to phase (check) for existance of these. Obviously if Directory exists dosnt work in this scenario so I came up with the following code.
Dim PhaseUri As New System.Uri(http://www.example.com/My_Folder)
Dim PhaseURL As String = PhaseUri.Host.ToString
If My.Computer.Network.IsAvailable AndAlso My.Computer.Network.Ping(PhaseURL, 1000) Then
Else
End If
The code checks if www.example.com exists by extracting it from the entire (http://www.example.com/My_Folder), its as close as I can get, however if www.example.com exists but My_Folder dosnt then I have a problem. Basicaly my above code gets me as close as possible and then makes a short leap of faith in assuming the rest will also exist.
How can I phase/ validate/ check for the existance of the entier http://www.example.com/My_Folder using less than 100,000 lines and as minimal complex code as possible?

It only works if your 'folder' is a webpage or contains a default document.
Works for a page, not folder
public function IsFolderOnline(url as string) as boolean
try
dim wc as new system.net.webclient()
wc.downloadstring(url)
return true
catch ex as exception
return false
end try
end function
use it like this:
dim IsItOnline as boolean = IsFolderOnline("http://example.org/folder")
it is not possible to get all pages within a folder
you must check every page for href elements to find new urls. It will only find urls that have a weblink.
Webclient.Downloadstring() downloads the html of a page.
use this code to retrieve all urls from the page
' Finding urls in the page
Dim FoundUrls As New List(Of String)
Dim strRegex As String = "<a[^<>]*>"
Dim myRegex As New Text.RegularExpressions.Regex(strRegex, System.Text.RegularExpressions.RegexOptions.None)
For Each myMatch As Text.RegularExpressions.Match In myRegex.Matches(html)
If myMatch.Success Then
Dim strRegex2 As String = "href=""[^""]*"""
Dim myRegex2 As New Text.RegularExpressions.Regex(strRegex, System.Text.RegularExpressions.RegexOptions.None)
For Each myMatch2 As Text.RegularExpressions.Match In myRegex.Matches(myMatch.Value)
If myMatch2.Success Then
Dim value As String = Split(Split(myMatch2.Value, """", 2).Last, """", 2).First
If value.ToLower.StartsWith("http://" & DomainName.ToLower) Then
FoundUrls.Add(value)
End If
If value.ToLower.StartsWith("https://" & DomainName.ToLower) Then
FoundUrls.Add(value)
End If
If value.ToLower.StartsWith("/") Then
FoundUrls.Add(Protocol & DomainName & value)
Else
If Not value.Contains(":") Then
FoundUrls.Add(Protocol & DomainName & "/" & value)
End If
End If
End If
Next
End If
Next
you might want to remove links that contain files
'Remove unsupported urls
Dim UnsupportedExtensions() As String = {".css", ".ico", ".xml", ".axd", ".js", ".zip", ".rar", ".7z", ".tar", ".jar", ".pdf", ".jpg", ".jpeg", ".png", ".bmp", ".mp4", ".mov", ".mpeg", ".gif"}
For Each url In FoundUrls.ToList
For Each UnsupportedExtension In UnsupportedExtensions
If url.ToLower.EndsWith(UnsupportedExtension) Then
FoundUrls.Remove(url)
Exit For
End If
Next
Next

Related

vb.net search directory for files containing *.G(num) but NOT *.GP(num)

I'm fairly familiar with bash, but I'm very, ***very**** new to vb.net. I'm searching for an easy way to find files in a folder that end with .G1, .G2, .G3, etc. but NOT .GP1, .GP2, .GP3, etc. Then for each file I need to copy it to another folder using a different file name but the same extension. I've managed to figure this out for the unique files, but there will be an undefined number of these depending on the project and I need to make sure that I get them all. Hard coding is possible, but very, very ugly. Any suggestions?
Here's the remnants of a failed attempt:
Public Sub FindGFiles()
FileList = IO.Directory.GetFiles(searchDir, ".G[1-99]" + , IO.SearchOption.AllDirectories)
For Each foundfile As String In FileList
If foundfile.Contains(".G#") Then
'copy file somehow and retain file extension
Else
MsgBox("No match")
End If
Next
End Sub
The GetFiles-method does only support * and ? wildcard characters.
So you have to get all files with a *.G*-extension first.
In the For Each-loop one can then use the Like-operator to check the desired pattern:
Public Sub CopyGFiles(searchDir As String, destDir As String)
Dim fileList As String() = IO.Directory.GetFiles(searchDir, "*.G*", IO.SearchOption.AllDirectories)
Dim fileName As String
Dim extension As String
For Each foundfile As String In fileList
fileName = IO.Path.GetFileNameWithoutExtension(foundfile)
extension = IO.Path.GetExtension(foundfile)
If extension Like ".G#" OrElse
extension Like ".G##" Then
'copy file to destination, append "_new" to the filename and retain file extension
IO.File.Copy(foundfile, IO.Path.Combine(destDir, fileName & "_new" & extension))
Else
'pattern not matched
End If
Next
End Sub
The method-call would then be as follows:
CopyGFiles("C:\Temp", "C:\Temp\Dest")
This should be done inside a Try/Catch as different exceptions can occur when working with files.
Try
CopyGFiles("C:\Temp", "C:\Temp\Dest")
Catch ex As Exception
MessageBox.Show("An error occured" + vbCrLf + ex.Message)
End Try

Why am I getting an error when I try to print the contents of a file I am searching for?

Can you help me with searching for and printing a file specified by text in textbox1? I have the following code but textbox1 shows me an error. I don't know if the code is correctly written and functioning right.
First class:
Public Class tisk
'print
Public Shared Function printers()
Dim printThis
Dim strDir As String
Dim strFile As String
Dim Textbox1 As String
strDir = "C:\_Montix a.s. - cloud\iMontix\Testy"
strFile = "C:\_Montix a.s. - cloud\iMontix\Testy\" & Textbox1.text & ".lbe"
If Not fileexprint.FileExists Then
MsgBox("Soubor neexistuje")
printers = False
Else
fileprint.PrintThisfile()
printers = True
End If
End Function
End Class
Second class:
Public Class fileprint
Public Shared Function PrintThisfile()
Dim formname As Long
Dim FileName As String
On Error Resume Next
Dim X As Long
X = Shell(formname, "Print", FileName, 0&)
End Function
End Class
Third class:
Public Class fileexprint
Public Shared Function FileExists()
Dim fname As Boolean
' Returns TRUE if the file exists
Dim X As String
X = Dir(fname)
If X <> "" Then FileExists = True _
Else FileExists = False
End Function
End Class
When I fill a textbox with text, how can I search for a file in the computer using this text and print this file?
Your "Textbox1" is a variable and not actually getting the value from a textbox. If I'm not wrong, I believe you intend to get the value of a textbox and concatenate to form your directory url. You'll first need to add a text box to your windows/web form, give that textbox an id then call that id in your code behind. E.g. You add a text box with id "textbox001", in your code behind you'll do something like "textbox001.text". In your case it'll now be: strFile = "C:_Montix a.s. - cloud\iMontix\Testy\" & textbox001.text & ".lbe". Hope this helps.
Not sure this will fix your issue, but there are some poor practices in that code that are addressed below. This will certainly get you closer than what you have right now.
Public Class tisk
'print
Public Shared Function printers(ByVal fileName As String) As Boolean
Dim basePath As String = "C:\_Montix a.s. - cloud\iMontix\Testy"
Dim filePath As String = IO.Path.Combine(basePath, fileName & ".lbe")
If IO.File.Exists(filePath) Then
fileprint.PrintThisfile(filePath)
Return True
End If
'Don't show a message box here. Do it in the calling code
Return False
End Function
End Class
Public Class fileprint
Public Shared Sub PrintThisfile(ByVal fileName As String)
'Not sure how well this will work, but it has better chances than the original
Dim p As New Process()
p.StartInfo.FileName = fileName
p.StartInfo.Verb = "Print"
p.Start()
End Sub
End Class
One additional comment on the File.Exists() check. It's actually poor practice to check if the file exists here at all. The file system is volatile. It's possible for things to change in the short time between when you check and when you try to use the file. In addition, whether the file exists is only one thing you need to look at. There's also access permissions and whether the file is locked or in use. The better practice is to just try to do whatever you need with the file, and then handle the exception if it fails.

new folders from a list, from a text file in vb.net

I want to be able to create new folders from a list that is stored in a text file.
The names are stored like
test1
test2
test3
so my code so far, loads the path to create the new folders, (which is the oldest folder in the given parent folder) stored in another text file "Foldercreation.txt"
then open the file with the names of the folders I want to create, "Folderstocreate.txt" and stores them all in filereader2.
but then when trying to create the folders for each line nothing happens.
My current code;
Dim fileReader, filereader2 As System.IO.StreamReader
Dim stringreader, parfolder As String
Dim path, foldername As List(Of String)
Dim count As Byte
If MsgBox("Are you sure you want to create these folders?,
Before clicking yes, make sure EVERYONE is out of paperport & you have entered the correct numbers.", MsgBoxStyle.YesNo, "WARNING!") = MsgBoxResult.Yes Then
If strnumbx.Text = "" Then
MsgBox("You have not entered a start number for the folders.", MsgBoxStyle.OkOnly, "Error")
End If
'Loads a text file at the given location, to read to.
fileReader = My.Computer.FileSystem.OpenTextFileReader("C:\Data\Test\Foldercreation.txt")
'Set stringreader as the read line from the file
stringreader = fileReader.ReadLine()
path = System.IO.Directory.GetDirectories(stringreader).ToList
path.Sort()
count = path.Count - 1
parfolder = path(count)
'System.IO.Directory.CreateDirectory(parfolder & "\test")
filereader2 = New StreamReader("C:\Data\Test\Folderstocreate.txt", True)
filereader2.ReadToEnd()
For Each line In filereader2.ReadToEnd()
System.IO.Directory.CreateDirectory(parfolder & fileReader.ReadToEnd(count - 1))
count = count + 1
Next
End If
fileReader.Close()
filereader2.Close()
This function would do it but you may want to put in some exception handling.
Directory.CreateDirectory will create all parent folders if they don't exist.
Private Sub CreateAllDirectories(ByVal strFileList As String)
Dim strDirectories As String() = File.ReadAllLines(strFileList)
For Each strDirectory As String In strDirectories
If Not Directory.Exists(strDirectory) Then
Directory.CreateDirectory(strDirectory)
End If
Next
End Sub

How to check if sub-folder text file exists

I am trying to search if a text file in a sub-folder exists.
This is the code I am using:
'Checks the program's root folder to see if the root folder exists.
Dim FolderName = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Cake Orders\" & TextBox1.Text))
Dim McKnwoll As String = Path.Combine(FolderName.FullName, Trim(TextBox2.Text) & (" ") & Trim(TextBox3.Text) + ".RTO")
If Not McKnwoll.Exists Then
‘Message to user that file does not exist in sub-folder
Else
‘Message to user that file does exists in sub-folder
End If
I am getting an error that 'Exists' is not a member of 'String'. How can I re-work my code to check if the text file whose name is in the format of "TextBox2.Text & (" ") & TextBox3.Text + ".RTO"; exists.
I am using Visual Basic 2010 Express. Thank you.
File.Exists returns a Boolean indicating whether a file at a certain path exists:
If File.Exists(pathToFile) Then
...
End If
Be sure to include Imports System.IO at the top of your source code file.
You seem quite new in programming. Welcome.
That error message you got ('Exists' is not a member of 'String') tells you exactely what is wrong: You try to ask a string (some text) whether it exists, but what you like to do is to ask a file whether it exists.
The class that provides information about a file is called "FileInfo", and FileInfo has an "Exists" property that you can call:
Dim myFileInfo As New FileInfo(McKnwoll)
If myFileInfo.Exists Then
'do something
End If
That's the object oriented answer, Heinzi's more service oriented one but works, of course, too.
There have been several other small issues I noticed with your code, e.g.
"Cake Orders\" & TextBox1.Text
does not use Path.Combine but makes a string concatenation using fix a "\" as directory separater. Or that the DirectoryInfo is not really used here, the string to the folder is enough.
You also try to handle 3 different issues (reading the values from the user interface, constructing the fullname of the file, checking whether the file exists) in one single code block. I would split them into 3 different ones (actually 4, I would add another one for displaying error messages).
Your simple few lines of codes could be complicated like this ;-)
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ReadFileIfPossible(TextBox1.Text, TextBox2.Text, TextBox3.Text)
End Sub
Private Sub ReadFileIfPossible(subfolder As String, part1 As String, part2 As String)
'Get the path to the RTO file
Dim myFilePath As String = Nothing
Try
myFilePath = GetRtoFilePath(subfolder, part1, part2)
Catch ex As Exception
DisplayErrorMessage("Error constructing file name! Please check the values of TextBox1, TextBox2 and TextBox3.")
Return
End Try
'Get the file info
Dim myFile As FileInfo = Nothing
Try
myFile = New FileInfo(myFilePath)
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Check whether it exists
Dim myExists As Boolean = False
Try
myExists = myFile.Exists 'it's IO, everything might throw an exception...
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Display message if not found
If (Not myExists) Then
DisplayErrorMessage("File ""{0}"" could not be found!", myFilePath)
Return
End If
'Read the file
Dim myLines As String() = Nothing
Try
myLines = File.ReadAllLines(myFile.FullName, New UTF8Encoding(True))
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Do something with it...
End Sub
Private Shared Function GetRtoFilePath(subfolder As String, part1 As String, part2 As String) As String
'Check args
If (subfolder Is Nothing) Then Throw New ArgumentNullException("subfolder")
If (part1 Is Nothing) Then Throw New ArgumentNullException("part1")
If (part2 Is Nothing) Then Throw New ArgumentNullException("part2")
'Normalize args
part1 = part1.Trim()
part2 = part2.Trim()
'Build path
Dim myDesktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim myFolderPath As String = Path.Combine(myDesktopPath, "Cake Orders")
myFolderPath = Path.Combine(myFolderPath, subfolder)
Dim myFileName As String = String.Format("{0} {1}.RTO", part1, part2)
Dim myResult As String = Path.Combine(myFolderPath, myFileName)
myResult = Path.GetFullPath(myResult)
'Return result
Return myResult
End Function
Private Sub DisplayErrorMessage(message As String, ParamArray args As Object())
Dim myMsg As String = String.Format(message, CType(args, Object()))
MsgBox(myMsg, MsgBoxStyle.OkOnly, "Error")
End Sub
End Class
Have fun.

ASP.NET How do I wait for file upload/release?

I've got ASP.NET intranet application written in VB. It gets a file from the user, and then depending on a few different cases it may create a few copies of the file as well as move the original.
Unfortunately I've come across a case where I get this error:
Exception Details: System.IO.IOException: The process cannot access the file
'\\some\dir\D09_03_5_180_0.000-6.788.png' because it is being used by
another process.
Which is thrown by My.Computer.FileSystem.CopyFile. And that's fine that it's being used by another process - it may still be saving/downloading from the user or trying to copy while another thread(?) is copying, I don't really care about that, what I want to know:
Is there any way that I can tell VB to wait to copy (also move) the file until the file is no longer in use?
Thanks
Test if the file is in use and the do what you need to do.
Public Sub WriteLogFile(ByVal pText As String, ByVal psPath As String, ByVal psName As String)
Dim strFullFileName As String
Dim Writer As System.IO.StreamWriter
Dim Fs As System.IO.FileStream
Try
Dim DirectoryHandler As New System.IO.DirectoryInfo(psPath)
strFullFileName = psPath & "\" & psName & Date.Today.Month.ToString & "-" & Date.Today.Day.ToString & "-" & Date.Today.Year.ToString & ".txt"
If Not DirectoryHandler.Exists() Then
Try
Monitor.Enter(fsLocker)
DirectoryHandler.Create()
Finally
Monitor.Exit(fsLocker)
End Try
End If
Try
If CheckIfFileIsInUse(strFullFileName) = True Then
Thread.Sleep(500) ' wait for .5 second
WriteLogFile(pText, psPath, psName)
If Not Fs Is Nothing Then Fs.Close()
If Not Writer Is Nothing Then Writer.Close()
Exit Sub
End If
Monitor.Enter(fsLocker)
Fs = New System.IO.FileStream(strFullFileName, IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.Write)
Writer = New System.IO.StreamWriter(Fs)
Writer.WriteLine(Date.Now.ToString & vbTab & "ProcessID: " & Process.GetCurrentProcess.Id.ToString() & vbTab & pText)
Writer.Close()
Fs.Close()
Finally
Monitor.Exit(fsLocker)
End Try
Catch ex As Exception
Dim evtEMailLog As System.Diagnostics.EventLog = New System.Diagnostics.EventLog()
evtEMailLog.Source = Process.GetCurrentProcess.ProcessName.ToString()
evtEMailLog.WriteEntry(ex.Message, System.Diagnostics.EventLogEntryType.Error)
Finally
If Not Fs Is Nothing Then Fs.Close()
If Not Writer Is Nothing Then Writer.Close()
End Try
End Sub
Public Function CheckIfFileIsInUse(ByVal sFile As String) As Boolean
If System.IO.File.Exists(sFile) Then
Try
Dim F As Short = FreeFile()
FileOpen(F, sFile, OpenMode.Append, OpenAccess.Write, OpenShare.Shared)
FileClose(F)
Catch
Return True
End Try
End If
End Function
Hmm... not directly.
What most implementations are doing, is making a retry of copying the file, with a small timeframe (some seconds)
if you want to make a nice UI, you check via Ajax, if the copying process went well.
Well, it turns out that waiting would not work in this case:
When trying to copy a file you cannot copy a file from one location to the same location or it will throw an error (apparently). Rather than just pretending to copy the file, VB actually tries to copy the file and fails because the copy operation is trying to copy to the file it's copying from (with overwrite:=True at least).
Whoops!