Podstawy programowania (4) dr Jerzy Bartoszek jbartoszek@wskiz.edu jerzy.bartoszek@put.poznan.pl
Obsługa plików Dim Nazwa as string="C:\1.txt" Dim NR as integer=Freefile() Dim Zmienna as string FileOpen(NR, Nazwa, OpenMode.Input) ' Output, Append ' wchodzimy w blok ochronny przed błędami Try ' odczytujemy dane z pliku aż napotkamy znak końca pliku(EOF) Do While Not EOF(NR) Zmienna = LineInput(NR) ' Print Loop Catch ex As Exception End Try FileClose(NR)
Obiektowa obsługa plików Przydatne składowe: przestrzeń nazw System.IO Klasy: FileStream, StreamReader, StreamWriter BinaryReader, BinaryWriter,
Zapisywanie do pliku tekstowego Dim fs As New System.IO.FileStream( _ "file.txt", FileMode.Create, _ FileAccess.Write) Dim w As New StreamWriter(fs) w.BaseStream.Seek(0, SeekOrigin.End) w.WriteLine("Here is the file's text.") w.Write("Here is more file text." & _ ControlChars.CrLf) w.WriteLine("And that's about it.") w.Flush() w.Close()
File FileStream StreamWriter fs w file.txt
Odczytywanie z pliku tekstowego Dim fs As New System.IO.FileStream( _ "file.txt", FileMode.Open, _ FileAccess.Read) Dim r As New StreamReader(fs) r.BaseStream.Seek(0, SeekOrigin.Begin) While r.Peek() > -1 Text &= r.ReadLine() & _ ControlChars.CrLf End While r.Close()
FileStream StreamReader File fs r file.txt
Zapisywanie do pliku binarnego Dim fs As New System.IO.FileStream( _ "data.txt", FileMode.Create, _ FileAccess.Write) Dim w As New BinaryWriter(fs) w.BaseStream.Seek(0, SeekOrigin.End) Dim LoopIndex As Int32 For LoopIndex = 0 To 19 w.Write(LoopIndex) Next w.Flush() w.Close()
Odczytywanie z pliku binarnego Dim fs As New System.IO.FileStream( _ "data.dat", FileMode.Open, _ FileAccess.Read) Dim r As New BinaryReader(fs) r.BaseStream.Seek(0, SeekOrigin.Begin) For LoopIndex = 0 To 19 Text &= r.ReadInt32() & _ ControlChars.CrLf r.Close()
Tworzenie katalogu Imports System.IO Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Directory.CreateDirectory(TextBox1.Text) Catch MsgBox("Could not create directory.") Exit Sub End Try MsgBox("Directory created.") End Sub End Class
Kopiowanie pliku Private Sub Button2_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles Button2.Click Try If OpenFileDialog1.ShowDialog <> DialogResult.Cancel Then File.Copy(OpenFileDialog1.FileName,TextBox1.Text & "\" & _ OpenFileDialog1.FileName.Substring( _ OpenFileDialog1.FileName.LastIndexOf("\"))) End If Catch MsgBox("Could not copy file.") Exit Sub End Try MsgBox("File copied.") End Sub