VB.Net Tutorial/Collections/Dictionary

Материал из VB Эксперт
Перейти к: навигация, поиск

Add object to Dictionary

<source lang="vbnet">Option Strict On Imports System.Collections.Generic Public Module modMain

  Private employees As Dictionary(Of String, Employee)
  Public Sub Main()
     employees = New Dictionary(Of String, Employee)
     employees.Add("name",New Employee("name", "1"))
     employees.Add("name1",New Employee("name1", "1"))
     Console.WriteLine("There are {0} employees now on file. They are:",employees.Count)
     For Each pair As KeyValuePair(Of String, Employee) In Employees
        Console.WriteLine(" {0}: {1}", pair.Key, pair.Value.Name)
     Next
  End Sub
     

End Module Public Class Employee

  Private empName As String
  Private empID As String
  Public Sub New(name As String, ID As String)
     Me.empName = name
     Me.empID = ID
  End Sub
  Public Property Name() As String
     Get
        Return Me.empName
     End Get
     Set
        Me.empName = Value
     End Set
  End Property
  Public Property ID As String
     Get
        return Me.empID
     End Get
     Set
        Me.empID = Value
     End Set
  End Property

End Class</source>

There are 2 employees now on file. They are:
 name: name
 name1: name1

Delete a Directory

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
   
   
       Directory.Delete("c:\\a")
   End Sub

End Class</source>

Delete a directory containing files and sub directories

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
   
       Try
           System.IO.Directory.Delete("c:\a", True)
       Catch ex As Exception
           Console.WriteLine(ex.ToString)
       Finally
           Beep()
       End Try
   
   End Sub

End Class</source>

Delete a directory with exception catch

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
   
       Try
           System.IO.Directory.Delete("c:\a")
       Catch ex As Exception
           Console.WriteLine(ex.ToString)
       Finally
           Beep()
       End Try
   
   End Sub

End Class</source>

System.IO.IOException: The directory is not empty.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
   at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
   at Tester.Main()

Dictionary(Of String, String)

<source lang="vbnet">Imports System.Collections.Generic Public Class GenericTest

  Public Shared Sub Main()
     Dim education As New Dictionary(Of String, String)
     education.Add("BA", "Bachelor of Arts")
     education.Add("BS", "Bachelor of Science")
     education.Add("MA", "Master of Arts")
     education.Add("MS", "Master of Science")
     education.Add("MPhil", "Master of Philosophy")
     education.Add("PhD", "Doctor of Philosophy")
     Console.WriteLine(education.Item("BS"))
     Console.WriteLine()
     For Each pair As KeyValuePair(Of String, String) In education
        Console.WriteLine(pair.Value)
     Next
  End Sub

End Class</source>

Bachelor of Science
Bachelor of Arts
Bachelor of Science
Master of Arts
Master of Science
Master of Philosophy
Doctor of Philosophy

Directory Exists

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
   
           If Directory.Exists("C:\\a") = True Then
              Console.WriteLine("true")
           End If
   End Sub

End Class</source>

Directory.GetFileSystemEntries

<source lang="vbnet">Imports System.IO public class Test

  public Shared Sub Main
       Dim aryItems() As String
       Dim strPath As String = "C:\Program Files"
       Dim strItem As String
       aryItems = Directory.GetFileSystemEntries(strPath)
       For Each strItem In aryItems
           If Directory.Exists(strItem) Then
               Console.WriteLine("FOLDER " & strItem)
           Else
               Console.WriteLine("FILE " & strItem)
           End If
       Next strItem
  End Sub

End class</source>

FOLDER C:\Program Files\Adobe
FOLDER C:\Program Files\AMD
FOLDER C:\Program Files\ATI Technologies
FOLDER C:\Program Files\Common Files
FOLDER C:\Program Files\ComPlus Applications
FOLDER C:\Program Files\CONEXANT
FOLDER C:\Program Files\ftp
FOLDER C:\Program Files\HPQ
FOLDER C:\Program Files\InstallShield Installation Information
FOLDER C:\Program Files\Internet Explorer
FOLDER C:\Program Files\Messenger
FOLDER C:\Program Files\microsoft frontpage
FOLDER C:\Program Files\Microsoft Office

Directory Move

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
   
           Directory.Move("c:\\b", "c:\\a")
           
   End Sub

End Class</source>

Get all directories under a directory

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
       Dim arrDirs() As String
       Dim strDir As String
       Try
           arrDirs = Directory.GetDirectories("c:\\")
           For Each strDir In arrDirs
               Console.WriteLine(strDir)
           Next
       Catch ex As Exception
           Console.WriteLine(ex.Message)
       End Try
   End Sub

End Class</source>

c:\\Documents and Settings
c:\\Java_Dev
c:\\oracle
c:\\Program Files
c:\\RECYCLER
c:\\System Volume Information
c:\\SYSTEM.SAV
c:\\Temp
c:\\WINDOWS

Get all directories under a directory with conditions

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
       Dim arrDirs() As String
       Dim strDir As String
       Try
           arrDirs = Directory.GetDirectories("c:\\","Wind*")
           For Each strDir In arrDirs
               Console.WriteLine(strDir)
           Next
       Catch ex As Exception
           Console.WriteLine(ex.Message)
       End Try
   End Sub

End Class</source>

c:\\WINDOWS

Get all files under a directory

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
       Dim arrDirs() As String
       Dim strDir As String
       Try
           arrDirs = Directory.GetFiles("c:\\")
           For Each strDir In arrDirs
               Console.WriteLine(strDir)
           Next
       Catch ex As Exception
           Console.WriteLine(ex.Message)
       End Try
   End Sub

End Class</source>

c:\\AUTOEXEC.BAT
c:\\boot.ini
c:\\CONFIG.SYS
c:\\DebugMessages.txt
c:\\hiberfil.sys
c:\\IO.SYS
c:\\MSDOS.SYS
c:\\NTDETECT.ru
c:\\ntldr
c:\\pagefile.sys
c:\\test.txt
c:\\test1.txt

Get all files under a directory with conditions

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
       Dim arrDirs() As String
       Dim strDir As String
       Try
           arrDirs = Directory.GetFiles("c:\\","*.sys")
           For Each strDir In arrDirs
               Console.WriteLine(strDir)
           Next
       Catch ex As Exception
           Console.WriteLine(ex.Message)
       End Try
   End Sub

End Class</source>

c:\\CONFIG.SYS
c:\\hiberfil.sys
c:\\IO.SYS
c:\\MSDOS.SYS
c:\\pagefile.sys

Get and set the current directory

<source lang="vbnet">Imports System.IO public class Test

  public Shared Sub Main
       Console.WriteLine("Current directory is " & Directory.GetCurrentDirectory & ".")
       Try
           Directory.SetCurrentDirectory("..\..\..\..\..\Temp")
           Console.WriteLine("Switched current folder to " & _
              Directory.GetCurrentDirectory & ".")
       Catch exc As FileNotFoundException
           Console.WriteLine("Invalid folder specified, currrent directory is " & _
              vbCrLf & Directory.GetCurrentDirectory & ".")
       Catch exc As Exception
           Console.WriteLine("Can"t access the specified folder.")
       End Try
  End Sub

End class</source>

Current directory is C:\Java_Dev\WEB\dev\VB.
Switched current folder to C:\Temp.

Get current directory: CurDir()

<source lang="vbnet">Option Strict On Public Class FileSystemTest

  Public Shared Sub Main()
     Console.WriteLine(CurDir())
  End Sub

End Class</source>

C:\Java_Dev\WEB\dev\VB

Get Directory Root

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
   
   
       Console.WriteLine(Directory.GetDirectoryRoot("c:\\Java_Dev"))
   End Sub

End Class</source>

c:\

Get Parent Directory

<source lang="vbnet">Imports System.IO Public Class Tester

   Public Shared Sub Main
   
   
       Console.WriteLine(Directory.GetParent("c:\\Java_Dev").ToString)
   End Sub

End Class</source>

c:\

Illustrate the pattern of using the Dir function. It is not intended to be compiled.

<source lang="vbnet">Option Strict On Public Module modErr

  Public Sub Main()
   Dim filename As String
   filename = Dir("*.*", FileAttribute.Normal)
   Do While Not filename = String.Empty
      Console.WriteLine(filename)
      filename = Dir()
   Loop
  End Sub

End Module</source>

String and custom class Dictionary

<source lang="vbnet">Imports System.Collections.Generic Public Structure Employee

  Dim Name As String
  Dim HireDate As Date
  Dim BirthDate As Date

End Structure Public Module Test

  Public Sub Main()
     Dim employees As New Dictionary(of String, Employee)
     Dim dateToFind As Date
     Dim input As String
     Dim emp As New Employee
     emp.Name = "S"
     emp.HireDate = #1/2/2003#
     emp.BirthDate = #7/12/1977#
     employees.Add(emp.Name, emp)
     emp.Name = "A"
     emp.HireDate = #8/18/1999#
     emp.BirthDate = #3/16/1964#
     employees.Add(emp.Name, emp)
     emp.Name = "B"
     emp.HireDate = #3/1/1987#
     emp.BirthDate = #11/12/1955#
     employees.Add(emp.Name, emp)
     dateToFind = CDate("7/12/1977")
     For Each employee As KeyValuePair(of String, Employee) In employees
        If Month(employee.Value.BirthDate) = Month(dateToFind) AndAlso Day(employee.Value.BirthDate) = Day(dateToFind) Then
           Console.WriteLine("{0:MMMM d} is the bithday of {1}.", dateToFind, employee.Key)
        End If
        
        If Month(employee.Value.HireDate) = Month(dateToFind) AndAlso Day(employee.Value.HireDate) = Day(dateToFind) Then
           Console.WriteLine("{0:MMMM d} is the hiring anniversary of {1}.", dateToFind, employee.Key)
        End If
     Next
  End Sub

End Module</source>

Use directories match

<source lang="vbnet">Imports System.IO public class Test

  public Shared Sub Main
       Dim aryDirs() As String
       Dim strDir As String
       aryDirs = Directory.GetDirectories("C:\Windows", "*SYSTEM*")
       Console.WriteLine(" folders match the pattern "*SYSTEM*".")
       For Each strDir In aryDirs
           Console.WriteLine(strDir)
       Next strDir
  End Sub

End class</source>

folders match the pattern "*SYSTEM*".
C:\Windows\system
C:\Windows\system32

Use MkDir to create a Directory

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
   
       MkDir("c:\\a")
   
   End Sub

End Class</source>

Use RmDir to delete a directory

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
      
   
       RmDir("c:\\a")
   End Sub

End Class</source>