Hack Forums
[.NET] Lot of VB.Net code's ! A must have ! - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [.NET] Lot of VB.Net code's ! A must have ! (/showthread.php?tid=110400)

Pages: Pages 1 2


Lot of VB.Net code's ! A must have ! - Inj3ction - Jul 28, 2009

+ Rep if you like it ! I will update it something.


How to get the machine name?
Code
Dim MachineName As String = Environment.MachineName
Console.WriteLine("Nom de la machine = {0}", MachineName)

Getting the version of my application?
Code
Dim ver As FileVersionInfo = FileVersionInfo.GetVersionInfo(Environment.GetCommandLineArgs()(0))
        Dim MyVer as String = ver.FileMajorPart & "." & ver.FileMinorPart & "." & ver.FileBuildPart & "." & ver.FilePrivatePart


Getting the version of. NET framework currently?
Code
'Version Framework
            Dim ver as Version = Environment.Version
            Console.WriteLine("Version Framework = {0}", ver)

Getting the Os version:
Code
Dim ver as Version = Environment.OSVersion
            Console.WriteLine("Version Framework = {0}", ver)


How to get the execution directory of my application?
Code
Dim exepath As String = Environment.GetCommandLineArgs()(0)
' Directory of the exe
Dim exedir As String = exepath.Substring(0, exepath.LastIndexOf("\"c))

How to get the system directory?
Code
'Repertoire systeme
    Console.WriteLine("Repertoire systeme = {0}", Environment.SystemDirectory)

How to get the name of the user whose session is in progress?

Code
Console.WriteLine("Nom utilisateur = {0}", Environment.UserName)


How to get the path of special folders like "My Documents"?

Code
'Répertoire spéciaux
        Console.WriteLine("Répertoire spéciaux")
        Dim specfolderenum As Array = [Enum].GetValues(GetType(Environment.SpecialFolder))
        For i As Integer = 0 To specfolderenum.Length - 1
            Console.WriteLine(Environment.GetFolderPath(CType(specfolderenum.GetValue(i), Environment.SpecialFolder)))
        Next


How can launch only one instance of my application?

Code
Imports System.Threading

Class SingleInstanceApp
    Implements IDisposable

    Private _siMutex As Mutex
    Private _siMutexOwned As Boolean

    Public Sub New(ByVal name As String)
        _siMutex = New Mutex(False, name)
        _siMutexOwned = False
    End Sub

    Public Function IsRunning() As Boolean
        _siMutexOwned = _siMutex.WaitOne(0, True)
        Return Not (_siMutexOwned)
    End Function

    Public Sub Dispose() Implements System.IDisposable.Dispose
        If _siMutexOwned Then
            _siMutex.ReleaseMutex()
        End If
    End Sub

End Class

To use our class, simply do so in the Main of our application.

Code
Shared Sub Main()
    Dim app As SingleInstanceApp = New SingleInstanceApp("{123456789 - ABCD - EFEG - XXXX}")
    Try
        If app.IsRunning Then
            MessageBox.Show("Application déjà lancée")
        Else
            Application.Run(New Form1)
        End If
    Finally
        CType(app, IDisposable).Dispose()
    End Try
End Sub

How to list running processes?

Code
Dim prc as System.Diagnostics.Process() = Process.GetProcesses()
Dim prc as System.Diagnostics.Process() = Process.GetProcessesByName("notepad")


How to stop a process?

Code
proc.CloseMainWindow()
proc.Close()


open a webpage in Iexplorer:
Code
Shell "C:\Program Files\Internet Explorer\IEXPLORE.EXE http://www.google.com

open a program:
Code
Shell "C:\Program Files\LOCATION OF PROGRAM.exe"


How to create, copy, move, delete a file?

Code
Imports System.IO

Module FileMan

    Sub Main()

        Try

            'Création d'un fichier vide.
            FileStream fs = File.Create("myfile.txt")
            fs.Close()
            Console.WriteLine("fichier myfile.txt créé")

            'Copie de fichier
            File.Copy("myfile.txt", "copyofmyfile.txt")
            Console.WriteLine("fichier myfile.txt copié vers copyofmyfile.txt")

            'Déplacement de fichier
            File.Move("copyofmyfile.txt", "c:\copyofmyfile.txt")
            Console.WriteLine("fichier copyofmyfile.txt déplacé vers c:\copyofmyfile.txt")

            'Supression fichier
            File.Delete("c:\copyofmyfile.txt")
            Console.WriteLine("Fichier c:\copyofmyfile.txt supprimé")

        Catch ex As Exception

            Debug.WriteLine(ex.ToString)
            Console.WriteLine(ex.Message)

        Finally

            'Fin du programme
            Console.WriteLine("Tapez sur entrée pour sortir ...")
            Console.ReadLine()

        End Try

    End Sub

End Module


How to get the attributes of a file or folder?

Code
Imports System.IO

Sub GetFileAttributes(ByVal sFilename As String)

Dim flagAttr As FileAttributes = File.GetAttributes(sFilename)
    
Console.WriteLine("Créé le {0} à {1}", _
File.GetCreationTime(sFilename).ToShortDateString, _
File.GetCreationTime(sFilename).ToShortTimeString)
    
Console.WriteLine("Modifié le {0} à {1}", _
File.GetLastWriteTime(sFilename).ToShortDateString, _
File.GetLastWriteTime(sFilename).ToShortTimeString)
    
Console.WriteLine("Dernier accès le {0} à {1}", _
File.GetLastAccessTime(sFilename).ToShortDateString, _
File.GetLastAccessTime(sFilename).ToShortTimeString)
    
Console.WriteLine("Attributs du fichier, lecteur ou repertoire {0}", sFilename)
    
If (flagAttr And FileAttributes.Archive) = FileAttributes.Archive Then
Console.WriteLine(FileAttributes.Archive.ToString)
End If

If (flagAttr And FileAttributes.Compressed) = FileAttributes.Compressed Then
Console.WriteLine(FileAttributes.Compressed.ToString)
End If

If (flagAttr And FileAttributes.Device) = FileAttributes.Device Then
Console.WriteLine(FileAttributes.Device.ToString)
End If

If (flagAttr And FileAttributes.Directory) = FileAttributes.Directory Then
Console.WriteLine(FileAttributes.Directory.ToString)
End If

If (flagAttr And FileAttributes.Encrypted) = FileAttributes.Encrypted Then
Console.WriteLine(FileAttributes.Encrypted.ToString)
End If
    
If (flagAttr And FileAttributes.Hidden) = FileAttributes.Hidden Then
Console.WriteLine(FileAttributes.Hidden.ToString)
End If

If (flagAttr And FileAttributes.Normal) = FileAttributes.Normal Then Console.WriteLine(FileAttributes.Normal.ToString)

If (flagAttr And FileAttributes.NotContentIndexed) = FileAttributes.NotContentIndexed Then
Console.WriteLine(FileAttributes.NotContentIndexed.ToString)
End If

If (flagAttr And FileAttributes.Offline) = FileAttributes.Offline Then
Console.WriteLine(FileAttributes.Offline.ToString)
End If

'Ne marche pas pour les répertoires apparemment
If (flagAttr And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
Console.WriteLine(FileAttributes.ReadOnly.ToString)
End If

If (flagAttr And FileAttributes.ReparsePoint) = FileAttributes.ReparsePoint Then
Console.WriteLine(FileAttributes.ReparsePoint.ToString)
End If

If (flagAttr And FileAttributes.SparseFile) = FileAttributes.SparseFile Then
Console.WriteLine(FileAttributes.SparseFile.ToString)
End If

If (flagAttr And FileAttributes.System) = FileAttributes.System Then
Console.WriteLine(FileAttributes.System.ToString)
End If

If (flagAttr And FileAttributes.Temporary) = FileAttributes.Temporary Then
Console.WriteLine(FileAttributes.Temporary.ToString)
End If

End Sub

How to read and write to a text file?

Code
Imports System.IO

Sub FichierTexte(ByVal NomFichier As String)
    Dim sr As StreamReader
    Dim sw As StreamWriter
    Dim sLine As String
    Try
        If Not File.Exists(NomFichier) Then
            'Le fichier n'existe pas. On le crée
            sw = New StreamWriter(NomFichier)
            sw.WriteLine("Bonjour. Il nous sommes le {0} et il est {1} ", _
DateTime.Now.ToLongDateString, _
DateTime.Now.ToLongTimeString)
            sw.Close()
            sw = Nothing
            'Remarque : On peut utiliser sw = File.AppendText(NomFichier) pour ajouter
            'du texte à un fichier existant
        End If
        'Ouverture du fichier et Ecriture du contenu du fichier sur la console
        sr = New StreamReader(NomFichier)
        Console.WriteLine("Debut du fichier")
        sLine = sr.ReadLine()
        While Not sLine Is Nothing
            Console.WriteLine(sLine)
            sLine = sr.ReadLine()
        End While
        Console.WriteLine("Fin du fichier")
    Finally
        'Fermeture streamreader
        If Not IsNothing(sr) Then sr.Close()
        'Fermeture streamwriter
        If Not IsNothing(sw) Then sw.Close()
    End Try
End Sub

How to read and write a binary file?

Code
Imports System.IO
    Sub FichierBinaire(ByVal NomFichier As String)
        Dim br As BinaryReader
        Dim bw As BinaryWriter
        Dim fs As FileStream
        Dim i As Integer
        Try
            If Not File.Exists(NomFichier) Then
                'Le fichier n'existe pas. On le crée
                bw = New BinaryWriter(File.Create(NomFichier))
                For i = 0 To 9
                    bw.Write(i)
                Next
                bw.Close()
            End If
            'Ouverture du fichier et Ecriture du contenu du fichier sur la console
            fs = File.Open(NomFichier, FileMode.Open)
            br = New BinaryReader(fs)
            Console.WriteLine("Debut du fichier")
            While fs.Position < fs.Length
                Console.Write(br.ReadInt32())
            End While
            Console.WriteLine("{0}Fin du fichier", ControlChars.CrLf)
        Finally
            'Fermeture Binaryreader
            If Not IsNothing(br) Then br.Close()
            'Fermeture Binarywriter
            If Not IsNothing(bw) Then bw.Close()
        End Try
    End Sub


How to test the existence of a file?

Code
If System.IO.File.Exists("c:\monFichier.txt") Then
            ' Le fichier existe
        Else
            ' Le fichier n'existe pas
        End If

How to retrieve the file extension?

Code
Private Function GetExtension(ByVal path As String) As String
  Return New System.IO.FileInfo(path).Extension
End Sub


How to compress a file with gzip?

Code
Imports System.IO
Imports System.IO.Compression


    Public Function compresserFichier(ByVal cheminSource As String, ByVal cheminDestination As String) As Boolean
        ' cheminSource : chemin complet du fichier à compresser
        ' cheminDestination : chemin complet du fichier compressé à créer
        Try
            ' Le fichier est placé dans le FileStream
            Dim monFileStream As New FileStream(cheminSource, FileMode.Open)

            Dim monBuffer(monFileStream.Length) As Byte
            ' Lecture de l'intégralité du FileStream
            monFileStream.Read(monBuffer, 0, CInt(monFileStream.Length))
            ' Fermeture du FileStream
            monFileStream.Close()
            ' Création du fichier qui va contenir le fichier compressé
            monFileStream = New FileStream(cheminDestination, FileMode.Create)
            ' Compression des données
            Dim monGZipStream As New GZipStream(monFileStream, CompressionMode.Compress, False)
            ' Ecriture des données compressées dans le fichier de destination
            monGZipStream.Write(monBuffer, 0, monBuffer.Length)
            ' Fermeture du GZipStream
            monGZipStream.Close()
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return False
        End Try
    End Function

How to decompress a gzip?

Code
Imports System.IO
Imports System.IO.Compression


    Public Function decompression(ByVal cheminSource As String, ByVal cheminDestination As String) As Boolean
        ' cheminSource : chemin complet du fichier compressé
        ' cheminDestination : chemin complet du fichier où le fichier doit être décompressé

        Try

            'Lecture du fichier compresse
            Dim monFileStream As New FileStream(cheminSource, FileMode.Open)
            ' Données du fichier placées dans un GZipStream
            Dim monGzipStream As New GZipStream(monFileStream, CompressionMode.Decompress)

            ' Tableau qui va contenir la taille du fichier
            Dim tailleOctets(3) As Byte

            ' Positionnement dans le Stream pour récupérer la taille
            Dim position As Integer = CInt(monFileStream.Length - 4)
            monFileStream.Position = position

            ' Récupération de la taille du fichier
            monFileStream.Read(tailleOctets, 0, 4)

            ' Repositionnement en début du Stream
            monFileStream.Position = 0

            ' Conversion de la taille du fichier en entier
            Dim tailleFichier As Integer = BitConverter.ToInt32(tailleOctets, 0)
            ' Dimesionnement du buffer
            Dim buffer(tailleFichier + 100) As Byte
            ' Offset qui permettra de se repérer dans le Stream
            Dim monOffset As Integer = 0


            While (True)

                ' Les données sont décompressées et placées dans le buffer
                Dim decompressionOctets As Integer = monGzipStream.Read(buffer, monOffset, 100)

                ' Tant qu'il reste des données on continue
                If (decompressionOctets = 0) Then
                    Exit While
                End If

                ' On icrémente l'offset pour ne pas repartir de 0 à chaque fois...
                monOffset += decompressionOctets

            End While

            ' Création du fichier décompressé
            monFileStream = New FileStream(cheminDestination, FileMode.Create)
            ' Ecriture des données décomrpessées dans le fichier
            monFileStream.Write(buffer, 0, tailleFichier - 1)

            ' Efface les données en mémoire tampon
            monFileStream.Flush()

            ' Fermeture des Streams
            monFileStream.Close()
            monGzipStream.Close()

            Return True

        Catch ex As Exception

            MessageBox.Show(ex.Message)
            Return False

        End Try

    End Function


How to rename a file?

Code
Dim monAncienFichier As String, monNouveauFichier As String
monAncienFichier = "toto.txt"
monNouveauFichier = "tata.txt"
File.Move(monAncienFichier, monNouveauFichier)


How do I change the file extension?
Code
Dim path As String = "C:\Test\test.xml"
Console.WriteLine("Nouveau path : {0}", System.IO.Path.ChangeExtension(path, "doc"))


Other Update coming soon ... and +rep if you like


- 88idiot88 - Jul 28, 2009

add this one

open a webpage in Iexplorer:
Code
Shell "C:\Program Files\Internet Explorer\IEXPLORE.EXE http://www.google.com"

open a program:
Code
Shell "C:\Program Files\LOCATION OF PROGRAM.exe"

i was just going to make this exact thread :P


- Sud0x3 - Jul 28, 2009

Nice snippets, im looking forward to seeing more.


- Xx1232shooterxX - Jul 28, 2009

You sir, are my hereo.


- GoldStar - Jul 28, 2009

good post, similar :
https://hackforums.net/showthread.php?tid=105994
https://hackforums.net/showthread.php?tid=95717
https://hackforums.net/showthread.php?tid=98985


- Sud0x3 - Jul 28, 2009

(Jul 28, 2009 06:44 AM)Miharbi Wrote:  good post, similar :
https://hackforums.net/showthread.php?tid=105994
https://hackforums.net/showthread.php?tid=95717
https://hackforums.net/showthread.php?tid=98985

Thanks for the links, do you know where i can find useful c++ snippets


- Apple - Jul 28, 2009

Wow, that's a lot of useful commands for getting information from a user :D


- KimeraSG1 - Jul 29, 2009

loved the text thing, i'll use it in my next bot then i'll give + rep if works :D


- Inj3ction - Jul 29, 2009

No prob Kimera SG1 tooshort


- Valour - Jul 29, 2009

good work

i have reported you as good poster


- Deathader - Jul 29, 2009

Good post mate :)

+rep


- Ethical Vox - Aug 8, 2009

Whoa always useful nice I like it I'll bookmark it. :)


- BETAhkr - Aug 8, 2009

Nice post but...
Code
Shell "C:\Program Files\Internet Explorer\IEXPLORE.EXE http://www.google.com

NO....!!!!!

use this
Code
Process.Start "www.hacforums.net"



- Inj3ction - Aug 8, 2009

thank' for your feedback and thank's for your rep ^^


- BETAhkr - Aug 8, 2009

Quote:
Thanks for the links, do you know where i can find useful c++ snippets


http://msdn.microsoft.com/en-us/visualc/default.aspx

This will answer any question you can type about C++ or you can switch
it up to VB .NET, C#, Etc.