Podstawy programowania 4 dr Jerzy Bartoszek jbartoszekwskiz edu
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 File. Open(NR, Nazwa, Open. Mode. 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 = Line. Input(NR) ' Print Loop Catch ex As Exception End Try File. Close(NR)
Obiektowa obsługa plików Przydatne składowe: • przestrzeń nazw System. IO • Klasy: – File. Stream, – Stream. Reader, – Stream. Writer – Binary. Reader, – Binary. Writer,
Zapisywanie do pliku tekstowego Dim fs As New System. IO. File. Stream( _ "file. txt", File. Mode. Create, _ File. Access. Write) Dim w As New Stream. Writer(fs) w. Base. Stream. Seek(0, Seek. Origin. End) w. Write. Line("Here is the file's text. ") w. Write("Here is more file text. " & _ Control. Chars. Cr. Lf) w. Write. Line("And that's about it. ") w. Flush() w. Close()
File file. txt File. Stream fs Stream. Writer w
Odczytywanie z pliku tekstowego Dim fs As New System. IO. File. Stream( _ "file. txt", File. Mode. Open, _ File. Access. Read) Dim r As New Stream. Reader(fs) r. Base. Stream. Seek(0, Seek. Origin. Begin) While r. Peek() > -1 Text &= r. Read. Line() & _ Control. Chars. Cr. Lf End While r. Close()
File file. txt File. Stream fs Stream. Reader r
Zapisywanie do pliku binarnego Dim fs As New System. IO. File. Stream( _ "data. txt", File. Mode. Create, _ File. Access. Write) Dim w As New Binary. Writer(fs) w. Base. Stream. Seek(0, Seek. Origin. End) Dim Loop. Index As Int 32 For Loop. Index = 0 To 19 w. Write(Loop. Index) Next w. Flush() w. Close()
Odczytywanie z pliku binarnego Dim fs As New System. IO. File. Stream( _ "data. dat", File. Mode. Open, _ File. Access. Read) Dim r As New Binary. Reader(fs) r. Base. Stream. Seek(0, Seek. Origin. Begin) For Loop. Index = 0 To 19 Text &= r. Read. Int 32() & _ Control. Chars. Cr. Lf r. Close()
Tworzenie katalogu Imports System. IO Public Class Form 1 Inherits System. Windows. Form Private Sub Button 1_Click(By. Val sender As System. Object, _ By. Val e As System. Event. Args) Handles Button 1. Click Try Directory. Create. Directory(Text. Box 1. Text) Catch Msg. Box("Could not create directory. ") Exit Sub End Try Msg. Box("Directory created. ") End Sub End Class
Kopiowanie pliku Private Sub Button 2_Click(By. Val sender As _ System. Object, By. Val e As System. Event. Args) _ Handles Button 2. Click Try If Open. File. Dialog 1. Show. Dialog <> Dialog. Result. Cancel Then File. Copy(Open. File. Dialog 1. File. Name, Text. Box 1. Text & "" & _ Open. File. Dialog 1. File. Name. Substring( _ Open. File. Dialog 1. File. Name. Last. Index. Of(""))) End If Catch Msg. Box("Could not copy file. ") Exit Sub End Try Msg. Box("File copied. ") End Sub
- Slides: 12