İzlenecek Yol: Visual Basic'te Dosyaları ve Dizinleri Düzenleme
Bu kılavuzda, dosya G/Ç ile ilgili temel Visual Basic. Bir dizinde metin dosyalarını listeleyen ve inceleyen küçük bir uygulamanın nasıl oluşturularak ilgili açıklamayı içerir. Uygulama, seçilen her metin dosyası için dosya öznitelikleri ve ilk içerik satırı sağlar. Günlük dosyasına bilgi yazma seçeneği vardır.
Bu izlenecek yol, içinde kullanılabilir My.Computer.FileSystem Object olan üyelerini Visual Basic. Daha fazla bilgi edinmek için bkz. FileSystem. Adım adım kılavuz sonunda, ad alanı sınıflarını kullanan eşdeğer bir örnek System.IO sağlanır.
Not
Bilgisayarınız, aşağıdaki yönergelerde yer alan Visual Studio kullanıcı arabirimi öğelerinden bazıları için farklı adlar veya konumlar gösterebilir. Sahip olduğunuz Visual Studio sürümü ve kullandığınız ayarlar bu öğeleri belirler. Daha fazla bilgi için bkz. IDE 'Yi kişiselleştirme.
Proje oluşturmak için
Dosya menüsünde Yeni Dosya'ya Project.
Yeni Proje iletişim kutusu görünür.
Yüklü Şablonlar bölmesinde, Visual Basic'yi genişletin ve ardından Windows. Ortadaki Şablonlar bölmesinde Formlar Uygulaması'Windows tıklayın.
Ad kutusuna yazarak
FileExplorerproje adını ayarlayın ve tamam'a tıklayın.Visual Studio proje Çözüm Gezgini ekler ve Windows Forms Tasarımcısı açılır.
Aşağıdaki tabloda yer alan denetimleri forma ekleyin ve özellikleri için karşılık gelen değerleri ayarlayın.
Denetim Özellik Değer ListBox Ad filesListBoxDüğme Ad
MetinbrowseButton
GözatDüğme Ad
MetinexamineButton
IncelemekCheckBox Ad
MetinsaveCheckBox
Sonuçları KaydetmeFolderbrowserdialog Ad FolderBrowserDialog1
Bir klasör seçmek ve bir klasördeki dosyaları listele
Formda
ClickdenetimebrowseButtonçift tıklayarak için bir olay işleyicisi oluşturun. Kod Düzenleyicisi açılır.Olay işleyiciye aşağıdaki
Clickkodu ekleyin.If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' List files in the folder. ListFiles(FolderBrowserDialog1.SelectedPath) End IfÇağrı,
FolderBrowserDialog1.ShowDialogKlasöre Gözat iletişim kutusunu açar. Kullanıcı Tamam'a tıkladığında, özelliği yöntemine bağımsız değişken olarak SelectedPath gönderilir ve sonraki adımdaListFileseklenir.Aşağıdaki yöntemi
ListFilesekleyin.Private Sub ListFiles(ByVal folderPath As String) filesListBox.Items.Clear() Dim fileNames = My.Computer.FileSystem.GetFiles( folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt") For Each fileName As String In fileNames filesListBox.Items.Add(fileName) Next End SubBu kod önce ListBox'ları temizler.
Yöntemi GetFiles daha sonra dizinde yer alan her dosya için bir dize koleksiyonuna sahip olur. yöntemi,
GetFilesbelirli bir desenle eşan dosyaları almak için bir arama deseni bağımsız değişkenini kabul eder. Bu örnekte yalnızca uzantıya sahip dosyalar .txt döndürülür.Yöntemi tarafından döndürülen
GetFilesdizeler daha sonra ListBox'a eklenir.Uygulamayı çalıştırın. Gözat düğmesine tıklayın. Klasöre Gözat iletişim kutusunda, dosya içeren bir klasöre .txt klasörü seçin ve Tamam'a tıklayın.
ListBox, seçilen klasördeki .txt dosya listesini içerir.Uygulamayı çalıştırmayı durdurun.
Bir dosyanın özniteliklerini ve metin dosyasından içerik almak için
Formda
ClickdenetimeexamineButtonçift tıklayarak için bir olay işleyicisi oluşturun.Olay işleyiciye aşağıdaki
Clickkodu ekleyin.If filesListBox.SelectedItem Is Nothing Then MessageBox.Show("Please select a file.") Exit Sub End If ' Obtain the file path from the list box selection. Dim filePath = filesListBox.SelectedItem.ToString ' Verify that the file was not removed since the ' Browse button was clicked. If My.Computer.FileSystem.FileExists(filePath) = False Then MessageBox.Show("File Not Found: " & filePath) Exit Sub End If ' Obtain file information in a string. Dim fileInfoText As String = GetTextForOutput(filePath) ' Show the file information. MessageBox.Show(fileInfoText)Kod, içinde bir öğenin seçili olduğunu
ListBoxdoğrular. Ardından dosya yolu girdisini dosyasındanListBoxediner. yöntemi, FileExists dosyanın hala mevcut olup olmadığını kontrol etmek için kullanılır.Dosya yolu, yöntemine bir bağımsız
GetTextForOutputdeğişken olarak gönderilir ve sonraki adımda eklenir. Bu yöntem, dosya bilgilerini içeren bir dize döndürür. Dosya bilgileri bir MessageBox içinde görünür.Aşağıdaki yöntemi
GetTextForOutputekleyin.Private Function GetTextForOutput(ByVal filePath As String) As String ' Verify that the file exists. If My.Computer.FileSystem.FileExists(filePath) = False Then Throw New Exception("File Not Found: " & filePath) End If ' Create a new StringBuilder, which is used ' to efficiently build strings. Dim sb As New System.Text.StringBuilder() ' Obtain file information. Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath) ' Add file attributes. sb.Append("File: " & thisFile.FullName) sb.Append(vbCrLf) sb.Append("Modified: " & thisFile.LastWriteTime.ToString) sb.Append(vbCrLf) sb.Append("Size: " & thisFile.Length.ToString & " bytes") sb.Append(vbCrLf) ' Open the text file. Dim sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(filePath) ' Add the first line from the file. If sr.Peek() >= 0 Then sb.Append("First Line: " & sr.ReadLine()) End If sr.Close() Return sb.ToString End FunctionKod, dosya GetFileInfo parametrelerini almak için yöntemini kullanır. Dosya parametreleri bir dosyasına StringBuilder eklenir.
yöntemi, OpenTextFileReader dosya içeriğini bir içine StreamReader okur. İçeriğin ilk satırı, 'den elde edilir
StreamReaderve 'yeStringBuildereklenir.Uygulamayı çalıştırın. Gözat 'a tıklayın ve dosya içeren bir klasöre .txt göz atabilirsiniz. Tamam'a tıklayın.
içinde bir dosya seçin ve
ListBoxardından İncele'ye tıklayın. ,MessageBoxdosya bilgilerini gösterir.Uygulamayı çalıştırmayı durdurun.
Günlük girişi eklemek için
Olay işleyicinin sonuna aşağıdaki
examineButton_Clickkodu ekleyin.If saveCheckBox.Checked = True Then ' Place the log file in the same folder as the examined file. Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt") Dim logText As String = "Logged: " & Date.Now.ToString & vbCrLf & fileInfoText & vbCrLf & vbCrLf ' Append text to the log file. My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True) End IfKod, günlük dosyasını seçilen dosyayla aynı dizine koymak için günlük dosyası yolunu ayarlar. Günlük girişinin metni, geçerli tarih ve saat olarak ve ardından dosya bilgilerine ayarlanır.
bağımsız WriteAllText değişkeni olarak ayarlanmış
appendTrueyöntemi, günlük girişini oluşturmak için kullanılır.Uygulamayı çalıştırın. Bir metin dosyasına göz at, içinde dosyayı
ListBoxseçin, Sonuçları Kaydet onay kutusunu seçin ve ardından İncele'ye tıklayın. Günlük girişinin dosyaya yazıldığılog.txtdoğrulayın.Uygulamayı çalıştırmayı durdurun.
Geçerli dizini kullanmak için
Forma çift tıklayarak
Form1_Loadiçin bir olay işleyicisi oluşturun.Olay işleyiciye aşağıdaki kodu ekleyin.
' Set the default directory of the folder browser to the current directory. FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectoryBu kod, klasör tarayıcısının varsayılan dizinini geçerli dizine ayarlar.
Uygulamayı çalıştırın. Gözat'a ilk kez tıklarsanız, Klasöre Gözat iletişim kutusu geçerli dizinde açılır.
Uygulamayı çalıştırmayı durdurun.
Denetimleri seçmeli olarak etkinleştirmek için
Aşağıdaki yöntemi
SetEnabledekleyin.Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End Subyöntemi,
SetEnablediçinde bir öğenin seçili olup olmadığına bağlı olarak denetimleri etkinleştiren veya devre dışı bıraktır.ListBoxFormda
SelectedIndexChangeddenetimefilesListBoxçift tıklayarak için birListBoxolay işleyicisi oluşturun.Yeni olay
SetEnabledişleyicisinde çağrısıfilesListBox_SelectedIndexChangedekleyin.Olay
SetEnabledişleyicinin sonuna çağrısıbrowseButton_Clickekleyin.Olay
SetEnabledişleyicinin sonuna çağrısıForm1_Loadekleyin.Uygulamayı çalıştırın. içinde bir öğe seçilmezse Sonuçları Kaydet onay kutusu ve İncele düğmesi devre dışı
ListBoxbırakılır.
My.Computer.FileSystem kullanan tam örnek
Aşağıda, tüm örnek verilmiştir.
' This example uses members of the My.Computer.FileSystem
' object, which are available in Visual Basic.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
SetEnabled()
End Sub
Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
End If
SetEnabled()
End Sub
Private Sub ListFiles(ByVal folderPath As String)
filesListBox.Items.Clear()
Dim fileNames = My.Computer.FileSystem.GetFiles(
folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
For Each fileName As String In fileNames
filesListBox.Items.Add(fileName)
Next
End Sub
Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If
' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString
' Verify that the file was not removed since the
' Browse button was clicked.
If My.Computer.FileSystem.FileExists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If
' Obtain file information in a string.
Dim fileInfoText As String = GetTextForOutput(filePath)
' Show the file information.
MessageBox.Show(fileInfoText)
If saveCheckBox.Checked = True Then
' Place the log file in the same folder as the examined file.
Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")
Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf
' Append text to the log file.
My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
End If
End Sub
Private Function GetTextForOutput(ByVal filePath As String) As String
' Verify that the file exists.
If My.Computer.FileSystem.FileExists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
' Obtain file information.
Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
' Add file attributes.
sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)
' Open the text file.
Dim sr As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(filePath)
' Add the first line from the file.
If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()
Return sb.ToString
End Function
Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
SetEnabled()
End Sub
Private Sub SetEnabled()
Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
System.IO kullanarak tam örnek
Aşağıdaki eşdeğer örnek, System.IO nesneleri kullanmak yerine ad alanından sınıfları kullanır My.Computer.FileSystem .
' This example uses classes from the System.IO namespace.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath =
System.IO.Directory.GetCurrentDirectory()
SetEnabled()
End Sub
Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
SetEnabled()
End If
End Sub
Private Sub ListFiles(ByVal folderPath As String)
filesListBox.Items.Clear()
Dim fileNames As String() =
System.IO.Directory.GetFiles(folderPath,
"*.txt", System.IO.SearchOption.TopDirectoryOnly)
For Each fileName As String In fileNames
filesListBox.Items.Add(fileName)
Next
End Sub
Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If
' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString
' Verify that the file was not removed since the
' Browse button was clicked.
If System.IO.File.Exists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If
' Obtain file information in a string.
Dim fileInfoText As String = GetTextForOutput(filePath)
' Show the file information.
MessageBox.Show(fileInfoText)
If saveCheckBox.Checked = True Then
' Place the log file in the same folder as the examined file.
Dim logFolder As String =
System.IO.Path.GetDirectoryName(filePath)
Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")
' Append text to the log file.
Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf
System.IO.File.AppendAllText(logFilePath, logText)
End If
End Sub
Private Function GetTextForOutput(ByVal filePath As String) As String
' Verify that the file exists.
If System.IO.File.Exists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
' Obtain file information.
Dim thisFile As New System.IO.FileInfo(filePath)
' Add file attributes.
sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)
' Open the text file.
Dim sr As System.IO.StreamReader =
System.IO.File.OpenText(filePath)
' Add the first line from the file.
If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()
Return sb.ToString
End Function
Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
SetEnabled()
End Sub
Private Sub SetEnabled()
Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub