Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Bu izlenecek yol, Visual Basic'teki dosya G/Ç'sinin temellerine giriş niteliğindedir. Bir dizindeki metin dosyalarını listeleyen ve inceleyen küçük bir uygulamanın nasıl oluşturulacağını açıklar. Uygulama, seçilen her metin dosyası için dosya özniteliklerini ve ilk içerik satırını sağlar. Günlük dosyasına bilgi yazma seçeneği vardır.
Bu açıklamalı anlatım, Visual Basic'te kullanılabilen My.Computer.FileSystem Object
üyelerini kullanır. Daha fazla bilgi için bkz. FileSystem. Yürütmenin sonunda, System.IO ad alanından sınıfları kullanan eşdeğer bir örnek sağlanır.
Uyarı
Bilgisayarınız, aşağıdaki yönergelerde bazı Visual Studio kullanıcı arabirimi öğeleri 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.
Projeyi oluşturmak için
Dosya menüsünde Yeni Proje'ye tıklayın.
Yeni Proje iletişim kutusu görünür.
Yüklü Şablonlar bölmesinde Visual Basic'i genişletin ve Windows'a tıklayın. Ortadaki Şablonlar bölmesinde Windows Forms Uygulaması'na tıklayın.
Ad kutusuna proje adını ayarlamak için yazın
FileExplorer
ve tamam'a tıklayın.Visual Studio projeyi Çözüm Gezgini'ne ekler ve Windows Forms Tasarımcısı açılır.
Aşağıdaki tablodaki denetimleri forma ekleyin ve özellikleri için karşılık gelen değerleri ayarlayın.
Yönetim Mülkiyet Değer ListBox İsim filesListBox
Düğmesi İsim
MetinbrowseButton
GözatDüğmesi İsim
MetinexamineButton
AraştırmakOnay Kutusu İsim
MetinsaveCheckBox
Sonuçları KaydetFolderBrowserDialog İsim FolderBrowserDialog1
Klasör seçmek ve klasördeki dosyaları listelemek için
Formdaki kontrol üzerinde çift tıklayarak
Click
için birbrowseButton
olay işleyicisi oluşturun. Kod Düzenleyicisi açılır.Click
olay işleyicisine aşağıdaki kodu ekleyin.If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' List files in the folder. ListFiles(FolderBrowserDialog1.SelectedPath) End If
Çağrı,
FolderBrowserDialog1.ShowDialog
Klasöre Gözat iletişim kutusunu açar. Kullanıcı Tamam düğmesine tıkladıktan sonra, SelectedPath özelliği bağımsız değişken olarak bir sonraki adımda eklenecek olanListFiles
yöntemine gönderilir.Aşağıdaki
ListFiles
yöntemi ekleyin.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
Bu kod ilk olarak ListBox'ını temizler.
Yöntemi GetFiles daha sonra dizindeki her dosya için bir dize koleksiyonu alır.
GetFiles
yöntemi, belirli bir desenle eşleşen dosyaları bulmak için bir arama deseni parametresinin alıcısıdır. Bu örnekte, yalnızca uzantı .txt olan dosyalar döndürülür.Yöntemi tarafından
GetFiles
döndürülen dizeler daha sonra ListBox'a eklenir.Uygulamayı çalıştırın. Gözat düğmesine tıklayın. Klasöre Gözat iletişim kutusunda, .txt dosyaları içeren bir klasöre gidin ve klasörü seçip Tamam'a tıklayın.
,
ListBox
seçili klasördeki .txt dosyalarının listesini içerir.Uygulamayı çalıştırmayı durdurun.
Bir dosyanın özniteliklerini ve metin dosyasından içerik almak için
Formdaki kontrol üzerinde çift tıklayarak
Click
için birexamineButton
olay işleyicisi oluşturun.Click
olay işleyicisine aşağıdaki kodu 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
ListBox
bir öğenin seçildiğini doğrular. Ardından dosya yolu girdisiniListBox
'den alır. FileExists yöntemi, dosyanın hala var olup olmadığını denetlemek için kullanılır.Dosya yolu, bir sonraki adımda eklenecek olan
GetTextForOutput
yöntemine bağımsız değişken olarak gönderilir. 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
GetTextForOutput
yöntemi ekleyin.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
Kod, dosya parametrelerini almak için yöntemini kullanır GetFileInfo . Dosya parametreleri bir StringBuilderöğesine eklenir.
OpenTextFileReader yöntemi, dosya içeriğini StreamReader içine okur. İçeriğin ilk satırı
StreamReader
'den alınır veStringBuilder
'e eklenir.Uygulamayı çalıştırın. Gözat'a tıklayın ve .txt dosyaları içeren bir klasöre göz atın. Tamam'a tıklayın.
içinde
ListBox
bir dosya seçin ve ardından İncele'ye tıklayın. AMessageBox
, dosya bilgilerini gösterir.Uygulamayı çalıştırmayı durdurun.
Günlük girdisi ekleme
Olay işleyicisinin
examineButton_Click
sonuna aşağıdaki kodu 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 If
Kod, günlük dosyasını seçilen dosyayla aynı dizine yerleştirmek için günlük dosyası yolunu ayarlar. Günlük girdisinin metni, önce geçerli tarih ve saate, ardından dosya bilgilerine ayarlanır.
WriteAllText yöntemi,
append
bağımsız değişkeniTrue
olarak ayarlanarak günlük girdisini oluşturmak için kullanılır.Uygulamayı çalıştırın. Bir metin dosyasına göz atın, içinde
ListBox
seçin, Sonuçları Kaydet onay kutusunu seçin ve ardından İncele'ye tıklayın. Günlük girdisininlog.txt
dosyasına yazıldığını kontrol edin.Uygulamayı çalıştırmayı durdurun.
Geçerli dizini kullanmak için
Forma çift tıklayarak
Form1_Load
için bir olay işleyicisi oluşturun.Olay işleyicisine aşağıdaki kodu ekleyin.
' Set the default directory of the folder browser to the current directory. FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
Bu kod, klasör tarayıcısının varsayılan dizinini geçerli dizine ayarlar.
Uygulamayı çalıştırın. İlk kez Gözat seçeneğine tıkladığınızda, Klasöre Gözat iletişim kutusu geçerli dizine açılır.
Uygulamayı çalıştırmayı durdurun.
Denetimleri seçmeli olarak etkinleştirmek için
Aşağıdaki
SetEnabled
yöntemi ekleyin.Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End Sub
yöntemi,
SetEnabled
içindeListBox
bir öğenin seçili olup olmamasına bağlı olarak denetimleri etkinleştirir veya devre dışı bırakır.Formdaki
SelectedIndexChanged
kontrolüne çift tıklayarak,filesListBox
için birListBox
olay işleyicisi oluşturun.Yeni
SetEnabled
olay işleyicisinefilesListBox_SelectedIndexChanged
çağrısı ekleyin.Olay işleyicisinin
SetEnabled
sonuna bir çağrıbrowseButton_Click
ekleyin.Olay işleyicisinin
SetEnabled
sonuna bir çağrıForm1_Load
ekleyin.Uygulamayı çalıştırın. içinde bir öğe seçilmediyse Sonuçları Kaydet onay kutusu ve
ListBox
düğmesi devre dışı bırakılır.
My.Computer.FileSystem kullanarak tam örnek
Aşağıda tam ö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 ad alanındaki sınıfları, My.Computer.FileSystem
nesnelerini kullanmak yerine kullanır.
' 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