Current User

‘retrieve current user identity
Dim wi As Security.Principal.WindowsIdentity = Security.Principal.WindowsIdentity.GetCurrent()
lblUserName.Text = wi.Name

App version

’set version number label
Dim ver As String = Application.ProductVersion
lblVersion.Text = “v” & ver.Substring(0, ver.Length-2)

’set title on application
Me.Text = My.Application.Info.ProductName & ” ” & lblVersion.Text

7zip and Visual Basic.net

Using 7zip from Visual Basic.net

Option Strict On

Imports System.ComponentModel

Public Class SevenZip

Private Shared ZipPath As String = AppController.RootPath & “7z.exe”

Public Event OnZipComplete(ByVal ZipFileName As String)

Public Shared Function Extract(ByVal filename As String, ByVal zipname As String) As Process
Dim p As New Process()
p.StartInfo.FileName = ZipPath
p.StartInfo.Arguments = “x -y -o”"” & filename & “”" “”" & zipname & “”"”
p.StartInfo.CreateNoWindow = True
p.Start()
Return p
End Function

Public Shared Function Compress(ByVal filename As String, ByVal zipname As String) As Process
Dim p As New Process()
p.StartInfo.FileName = ZipPath
p.StartInfo.Arguments = “a -r -tzip “”" & zipname & “”" “”" & filename & “”"”
p.StartInfo.CreateNoWindow = True
p.Start()
Return p
End Function

Public Shared Function Compress(ByVal filename As String, ByVal zipnames() As String) As Process
Dim p As New Process()
p.StartInfo.FileName = ZipPath

Dim args As String = “a -r -tzip ”
Dim s As String

For Each s In zipnames
args &= “”"” & s & “”" ”
Next

p.StartInfo.Arguments = args & filename & “”"”
p.StartInfo.CreateNoWindow = True
p.Start()
Return p
End Function

Private Structure FileCopy
Public Source As String
Public Destination As String

Public Sub New(ByVal source As String, ByVal dest As String)
Me.Source = source
Me.Destination = dest
End Sub
End Structure

Public Sub CompressInNewThread(ByVal filename As String, ByVal zipname As String)
Dim fc As New FileCopy(filename, zipname)

‘run zip compress in another thread
bw = New System.ComponentModel.BackgroundWorker()
bw.RunWorkerAsync(fc)
End Sub

Private WithEvents bw As BackgroundWorker

Private Sub StartZip(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bw.DoWork
Dim fc As FileCopy = DirectCast(e.Argument, FileCopy)

Dim p As New Process()
p.StartInfo.FileName = ZipPath
p.StartInfo.Arguments = “a -r -tzip “”" & fc.Destination & “”" “”" & fc.Source & “”"”
p.Start()
p.WaitForExit()

‘return the zip filepath
e.Result = fc.Destination
End Sub

Private Sub EndZip(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
RaiseEvent OnZipComplete(Convert.ToString(e.Result))
End Sub

End Class

Test for Internet Connection

Public Function GotInternet() As Boolean
Dim req As System.Net.HttpWebRequest
Dim res As System.Net.HttpWebResponse
GotInternet = False
Try
req = CType(System.Net.HttpWebRequest.Create(“http://www.google.com”), System.Net.HttpWebRequest)
res = CType(req.GetResponse(), System.Net.HttpWebResponse)
req.Abort()
If res.StatusCode = System.Net.HttpStatusCode.OK Then
GotInternet = True
End If
Catch weberrt As System.Net.WebException
GotInternet = False
Catch except As Exception
GotInternet = False
End Try
End Function

File downloader

Download multiple files listed as filenames in a text file.

Public Class Form1

Private Const filenames As String = “c:\files.txt”
Private Const url As String = “http://awebsite.com/files/”
Private Const savepath As String = “c:\folderonpc\”

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sr As New IO.StreamReader(filenames)
Dim line As String = sr.ReadLine()

Dim req As Net.WebRequest
Dim resp As IO.Stream
Dim out As IO.BinaryWriter

Do While line IsNot Nothing
req = Net.HttpWebRequest.Create(url & line)
resp = req.GetResponse().GetResponseStream()

out = New IO.BinaryWriter(New IO.FileStream(savepath & line, IO.FileMode.OpenOrCreate))

Dim buf(4096) As Byte
Dim k As Int32 = resp.Read(buf, 0, 4096)

Do While k > 0
out.Write(buf, 0, k)
k = resp.Read(buf, 0, 4096)
Loop

resp.Close()
out.Close()

line = sr.ReadLine()
Loop

End Sub

End Class

Geturl function

Public Function GetUrl() As String
Dim strTemp As String = “”
If (Request.ServerVariables(“HTTPS”) = “on”) Then
strTemp = “https://”
Else
strTemp = “http://”
End If
strTemp = (strTemp + Request.ServerVariables(“SERVER_NAME”))
If (Request.ServerVariables(“SERVER_PORT”) <> “80″) Then
strTemp = (strTemp + (“:” + Request.ServerVariables(“SERVER_PORT”)))
End If
strTemp = (strTemp + Request.ApplicationPath)
Return strTemp
End Function

Recursion example

Private Sub RecurseDir(ByVal path As String)
Dim s As String

‘recurse down through each folder
For Each s In IO.Directory.GetDirectories(path)
RecurseDir(s)
Next

‘then print files
For Each s In IO.Directory.GetFiles(path)
Console.WriteLine(s)
Next
End Sub

Ping an IP address

My.Computer.Network.Ping(targetSystem[, timeout])

targetSystem is a string IP address, a host name, or a System.Uri instance. The optional timeout argument is supplied in milliseconds and defaults to 500.

This method returns true if the ping is successful, or False on failure or no response.

To ping localhost for example you would have the following

My.Computer.Network.Ping(127.0.0.1timeout])

Does a directory exist

Create a new Windows Forms application, and add a TextBox control named TextBox1 and a Button control named Button1 to the form. Now add the following code:

 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

       If (My.Computer.FileSystem.DirectoryExists(TextBox1.Text)) Then
          MsgBox("The directory already exists.")
       Else
          MsgBox("The directory does not exist.")
       End If
    End Sub

Number of days in a month

Dim daysInMonth As Integer = Date.DaysInMonth(Now.Year, Now.Month)

MsgBox(String.Format("Number of days in the current month: {0}", daysInMonth))