VB.Net/File Directory/Directory — различия между версиями

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

Текущая версия на 12:45, 26 мая 2010

Directory Information: name, last update and create time

Imports System.IO
Module Module1
    Sub Main()
            Dim Dir As New DirectoryInfo("C:\WINNT\Temp")
            Console.WriteLine("Full name: {0}", Dir.FullName)
            Console.WriteLine("Creation time: {0}", Dir.CreationTime)
            Console.WriteLine("Last access time: {0}", Dir.LastAccessTime)
            Console.WriteLine("Last write time: {0}", Dir.LastWriteTime)
    End Sub
End Module


Directory Separator

Imports System.IO
Module Module1
    Sub Main()
        Console.WriteLine("Directory Separator {0}", Path.DirectorySeparatorChar)
    End Sub
End Module


Display all file under a Directory

Imports System
Imports System.IO
Public Class MainClass
   Shared Sub Main()
         Dim fileName As String
         fileName = "C:\"
         
            Dim directoryList As String() " array for directories
            Dim i As Integer
            directoryList = Directory.GetDirectories(fileName)
            Console.WriteLine("Directory contents:" )
            " output directoryList contents
            For i = 0 To directoryList.Length - 1
               Console.WriteLine( directoryList(i) )
            Next
   End Sub " Main
End Class


Display Directory Tree

Imports System.IO
Module Module1
    Sub DisplayTree(ByVal Dir As String)
        Dim Files As String() = Directory.GetFiles(Dir)
        Dim Dirs As String() = Directory.GetDirectories(Dir)
        Dim Filename As String
        For Each Filename In Files
            Console.WriteLine(Filename)
        Next
        Dim DirectoryName As String
        For Each DirectoryName In Dirs
            DisplayTree(DirectoryName)
        Next
    End Sub
    Sub Main()
        DisplayTree("C:\")
    End Sub
End Module


Find a file: search directory recursively

Imports System
Imports System.Windows.Forms
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Collections.Specialized
Public Class MainClass
   Shared Sub Main()
        Dim myform As Form = New FrmFileSearch()
        Application.Run(myform)
   End Sub " Main
End Class
 
Public Class FrmFileSearch
   Inherits Form
   " label that displays current directory
   Friend WithEvents lblDirectory As Label
   " label that displays directions to user
   Friend WithEvents lblDirections As Label
   " button that activates search
   Friend WithEvents cmdSearch As Button
   " text boxes for inputting and outputting data
   Friend WithEvents txtInput As TextBox
   Friend WithEvents txtOutput As TextBox
#Region " Windows Form Designer generated code "
   Public Sub New()
      MyBase.New()
      "This call is required by the Windows Form Designer.
      InitializeComponent()
      "Add any initialization after the InitializeComponent() call
   End Sub
   "Form overrides dispose to clean up the component list.
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing Then
         If Not (components Is Nothing) Then
            components.Dispose()
         End If
      End If
      MyBase.Dispose(disposing)
   End Sub
   "Required by the Windows Form Designer
   Private components As System.ruponentModel.Container
   "NOTE: The following procedure is required by the Windows Form Designer
   "It can be modified using the Windows Form Designer.  
   "Do not modify it using the code editor.
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
      Me.txtOutput = New System.Windows.Forms.TextBox()
      Me.lblDirections = New System.Windows.Forms.Label()
      Me.lblDirectory = New System.Windows.Forms.Label()
      Me.txtInput = New System.Windows.Forms.TextBox()
      Me.cmdSearch = New System.Windows.Forms.Button()
      Me.SuspendLayout()
      "
      "txtOutput
      "
      Me.txtOutput.AutoSize = False
      Me.txtOutput.BackColor = System.Drawing.SystemColors.Control
      Me.txtOutput.Location = New System.Drawing.Point(20, 276)
      Me.txtOutput.Multiline = True
      Me.txtOutput.Name = "txtOutput"
      Me.txtOutput.ReadOnly = True
      Me.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
      Me.txtOutput.Size = New System.Drawing.Size(461, 208)
      Me.txtOutput.TabIndex = 4
      Me.txtOutput.Text = ""
      "
      "lblDirections
      "
      Me.lblDirections.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.lblDirections.Location = New System.Drawing.Point(20, 138)
      Me.lblDirections.Name = "lblDirections"
      Me.lblDirections.Size = New System.Drawing.Size(451, 20)
      Me.lblDirections.TabIndex = 1
      Me.lblDirections.Text = "Enter Path to Search:"
      "
      "lblDirectory
      "
      Me.lblDirectory.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.lblDirectory.Location = New System.Drawing.Point(20, 20)
      Me.lblDirectory.Name = "lblDirectory"
      Me.lblDirectory.Size = New System.Drawing.Size(451, 98)
      Me.lblDirectory.TabIndex = 0
      Me.lblDirectory.Text = "Current Directory:"
      "
      "txtInput
      "
      Me.txtInput.Location = New System.Drawing.Point(20, 168)
      Me.txtInput.Name = "txtInput"
      Me.txtInput.Size = New System.Drawing.Size(461, 22)
      Me.txtInput.TabIndex = 3
      Me.txtInput.Text = ""
      "
      "cmdSearch
      "
      Me.cmdSearch.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.cmdSearch.Location = New System.Drawing.Point(20, 217)
      Me.cmdSearch.Name = "cmdSearch"
      Me.cmdSearch.Size = New System.Drawing.Size(461, 40)
      Me.cmdSearch.TabIndex = 2
      Me.cmdSearch.Text = "Search Directory"
      "
      "FrmFileSearch
      "
      Me.AutoScaleBaseSize = New System.Drawing.Size(6, 15)
      Me.ClientSize = New System.Drawing.Size(501, 499)
      Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.txtOutput, Me.txtInput, Me.cmdSearch, Me.lblDirections, Me.lblDirectory})
      Me.Name = "FrmFileSearch"
      Me.Text = "Using Regular Expressions"
      Me.ResumeLayout(False)
   End Sub
#End Region
   Dim currentDirectory As String = Directory.GetCurrentDirectory
   Dim directoryList As String()
   Dim fileArray As String() 
 
   Dim found As NameValueCollection = New NameValueCollection()
  
   Private Sub txtInput_KeyDown(ByVal sender As System.Object, _
      ByVal e As System.Windows.Forms.KeyEventArgs) _
      Handles txtInput.KeyDown
    
      If (e.KeyCode = Keys.Enter) Then
         cmdSearch_Click(sender, e)
      End If
   End Sub 
 
   Private Sub cmdSearch_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles cmdSearch.Click
      Dim current As String
    
      If txtInput.Text <> "" Then
         " verify that user input is a valid directory name
         If Directory.Exists(txtInput.Text) Then
            currentDirectory = txtInput.Text
            " reset input text box and update display
            lblDirectory.Text = "Current Directory:" & vbCrLf & _
              currentDirectory
            " show error if user does not specify valid directory
         Else
            MessageBox.Show("Invalid Directory", "Error", _
               MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return
         End If
      End If
      " clear text boxes
      txtInput.Text = ""
      txtOutput.Text = ""
      " search directory
      SearchDirectory(currentDirectory)
      " summarize and print results
      For Each current In found
         txtOutput.Text &= "* Found " & found(current) & " " _
            & current & " files." & vbCrLf
      Next
      " clear output for new search
      found.Clear()
   End Sub " cmdSearch_Click
   " search directory using regular expression
   Private Sub SearchDirectory(ByVal currentDirectory As String)
      " for file name without directory path
      Try
         Dim fileName As String = ""
         Dim myFile As String
         Dim myDirectory As String
         " regular expression for extensions matching pattern
         Dim regularExpression As Regex = _
            New Regex("([a-zA-Z0-9]+\.(?<extension>\w+))")
         " stores regular-expression-match result 
         Dim matchResult As Match
         Dim fileExtension As String " holds file extensions
         " number of files with given extension in directory
         Dim extensionCount As Integer
         " get directories
         directoryList = _
            Directory.GetDirectories(currentDirectory)
         " get list of files in current directory
         fileArray = Directory.GetFiles(currentDirectory)
         " iterate through list of files
         For Each myFile In fileArray
           
            fileName = myFile.Substring( _
               myFile.LastIndexOf("\") + 1)
           
            matchResult = regularExpression.Match(fileName)
           
            If (matchResult.Success) Then
               fileExtension = matchResult.Result("${extension}")
            Else
               fileExtension = "[no extension]"
            End If
           
            If (found(fileExtension) = Nothing) Then
               found.Add(fileExtension, "1")
            Else
               extensionCount = _
                  Convert.ToInt32(found(fileExtension)) + 1
               found(fileExtension) = extensionCount.ToString()
            End If

         Next
       
         For Each myDirectory In directoryList
            SearchDirectory(myDirectory)
         Next
       
      Catch unauthorizedAccess As UnauthorizedAccessException
         MessageBox.Show("Some files may not be visible due to" _
            & " permission settings", "Warning", _
            MessageBoxButtons.OK, MessageBoxIcon.Information)
      End Try
   End Sub
End Class


Get all directories

Imports System
Imports System.IO
Public Class MainClass
  Shared Sub Main()
    Dim curDir, nextDir As String
    Try
      curDir = Directory.GetCurrentDirectory()
      Console.WriteLine(curDir)
      For Each nextDir In Directory.GetDirectories(curDir)
        Console.WriteLine(nextDir)
      Next
    Catch ioe As IOException
      Console.WriteLine("i/o problems!" & ioe.Message)
    Catch e As Exception
      Console.Write(e.StackTrace)
    Finally
      Console.Write("Done")
    End Try
  End Sub
  
End Class


Get Current Directory

Imports System

Public Class MainClass
   Shared Sub Main()
        Console.WriteLine("CurrentDirectory:   " & System.Environment.CurrentDirectory )
   End Sub 
End Class


Get file in the parent folder

Imports System
Imports System.Windows.Forms
Public Class MainClass
   Shared Sub Main()
        Dim file_name As String = Application.StartupPath
        file_name = file_name.Substring(0, file_name.LastIndexOf("\"))
        file_name = file_name.Substring(0, file_name.LastIndexOf("\"))
        file_name &= "\test.vb"
        Console.WriteLine( file_name)
   End Sub 
End Class


Get Root directory and current directory

Imports System.IO
Module Module1
    Sub Main()
        Dim Current As String
        Dim Root As String
        Try
            Current = Directory.GetCurrentDirectory()
            Root = Directory.GetDirectoryRoot(Current)
            Root = Directory.GetDirectoryRoot("\")
            Console.WriteLine("Current directory {0}", Current)
            Console.WriteLine("Root directory {0}", Root)
        Catch E As Exception
            Console.WriteLine("Error determining root directory")
            Console.WriteLine(E.Message)
        End Try
    End Sub
End Module


List files and directories in root

Imports System.IO
Module Module1
    Sub Main()
        Dim Files As String() = Directory.GetFiles("C:\")
        Dim Dirs As String() = Directory.GetDirectories("C:\")
        Console.WriteLine("Root Files")
        Dim Filename As String
        For Each Filename In Files
            Console.WriteLine(Filename)
        Next
        Console.WriteLine("Root Directories")
        Dim DirectoryName As String
        For Each DirectoryName In Dirs
            Console.WriteLine(DirectoryName)
        Next
    End Sub
End Module


Recursive Directory Info

Imports System
Imports System.IO
Public Class MainClass
  Shared Sub Main()
    Dim nameOfDirectory As String = "C:\"
    Dim myDirectory As DirectoryInfo
    myDirectory = New DirectoryInfo(nameOfDirectory)
    WorkWithDirectory(myDirectory)
  End Sub
  Shared Public Sub WorkWithDirectory(ByVal aDir As DirectoryInfo)
    Dim nextDir As DirectoryInfo
    WorkWithFilesInDir(aDir)
    For Each nextDir In aDir.GetDirectories
      WorkWithDirectory(nextDir)
    Next
  End Sub
  Shared Public Sub WorkWithFilesInDir(ByVal aDir As DirectoryInfo)
    Dim aFile As FileInfo
    For Each aFile In aDir.GetFiles()
      Console.WriteLine(aFile.FullName)
    Next
  End Sub
  
End Class


Update Directory: create time, last access time and last write time

Imports System.IO
Module Module1
    Sub Main()
        If (Directory.Exists("C:\WINNT\Temp")) Then
            Dim Dir As New DirectoryInfo("C:\WINNT\Temp")
            Dim DateTimeNow As DateTime = DateTime.Now()
            Try
                Dir.CreationTime = DateTimeNow
                Dir.LastAccessTime = DateTimeNow
                Dir.LastWriteTime = DateTimeNow
                Console.WriteLine("Directory attributes updated")
            Catch E As Exception
                Console.WriteLine("Error updating attributes")
                Console.WriteLine("Error {0}: ", E.Message)
            End Try
        Else
            Console.WriteLine("C:\WINNT\Temp does not exist")
        End If
    End Sub
End Module