VB.Net Tutorial/Collections/Dictionary

Материал из VB Эксперт
Версия от 12:53, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Add object to Dictionary

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
There are 2 employees now on file. They are:
 name: name
 name1: name1

Delete a Directory

Imports System.IO
Public Class Tester
    Public Shared Sub Main
    
    
        Directory.Delete("c:\\a")
    End Sub
End Class

Delete a directory containing files and sub directories

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

Delete a directory with exception catch

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
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)

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
Bachelor of Science
Bachelor of Arts
Bachelor of Science
Master of Arts
Master of Science
Master of Philosophy
Doctor of Philosophy

Directory Exists

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

Directory.GetFileSystemEntries

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
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

Imports System.IO
Public Class Tester
    Public Shared Sub Main
    
            Directory.Move("c:\\b", "c:\\a")
            
    End Sub
End Class

Get all directories under a directory

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
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

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
c:\\WINDOWS

Get all files under a directory

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
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

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
c:\\CONFIG.SYS
c:\\hiberfil.sys
c:\\IO.SYS
c:\\MSDOS.SYS
c:\\pagefile.sys

Get and set the current directory

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
Current directory is C:\Java_Dev\WEB\dev\VB.
Switched current folder to C:\Temp.

Get current directory: CurDir()

Option Strict On
Public Class FileSystemTest
   Public Shared Sub Main()
      Console.WriteLine(CurDir())
   End Sub
End Class
C:\Java_Dev\WEB\dev\VB

Get Directory Root

Imports System.IO
Public Class Tester
    Public Shared Sub Main
    
    
        Console.WriteLine(Directory.GetDirectoryRoot("c:\\Java_Dev"))
    End Sub
End Class
c:\

Get Parent Directory

Imports System.IO
Public Class Tester
    Public Shared Sub Main
    
    
        Console.WriteLine(Directory.GetParent("c:\\Java_Dev").ToString)
    End Sub
End Class
c:\

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

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

String and custom class Dictionary

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

Use directories match

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
folders match the pattern "*SYSTEM*".
C:\Windows\system
C:\Windows\system32

Use MkDir to create a Directory

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

Use RmDir to delete a directory

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