PB.NET II (System.IO)
-
Upload
guestca2f46d -
Category
Documents
-
view
2.486 -
download
1
description
Transcript of PB.NET II (System.IO)
![Page 1: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/1.jpg)
Wykład II: Wejścia i wyjścia (System.IO)
Karim AghaKarol RogowskiAdam Rafałko
![Page 2: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/2.jpg)
Co dziś omówimy ?
Operacje na plikach używając klas zawartych w System.IO.
Strumienie. Jak używać klas Reader i Writer. Kompresja danych. Isolated Storage. Projekt Grupy PB.NET
![Page 3: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/3.jpg)
Co powinniśmy już umieć ? Utworzyć nowy projekt konsolowy w
Microsoft Visual Studio dla C# lub VB. Dodać referencję do projektu. Utworzyć plik tekstowy.
![Page 4: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/4.jpg)
Nawigacja po systemie plików System.IO zawiera takie klasy które pozwalają na
nawigację i manipulację plików:Klasy Informacyjne (FileInfo, DirectoryInfo)Klasy narzędziowe (File, Directory, Path)
![Page 5: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/5.jpg)
Klasy Informacyjne
Dziedziczą po FileSystemInfo. Klasy te nazywają się:
FileInfoDirectoryInfoDriveInfo*
Służą głównie do pozyskiwania informacji o plikach, katalogach lub dyskach.
![Page 6: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/6.jpg)
Klasy Informacyjne cd.Właściwość Opis
Attributes Zwraca objekt FileAttributes dla danego pliku lub katalogu.
CreationTime Date utworzenia pliku/katalogu.
Exists Informuje o tym czy plik/katalog istnieje.
Extension Rozszerzenie.
FullName Pełna ścieżka do pliku/katalogu.
LastAccessTime Data ostatniego odczytu.
LastWriteTime Data ostatniego zapisu
Name Prosta nazwa: plik: C:\Program Files\PB.NET\plik.txt: ->plik.txt katalog: C:\Program Files\PB.NET\ ->PB.NET
Najważniejsze właściwości klasy FileSystemInfo.
![Page 7: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/7.jpg)
Klasy InformacyjneMetoda Opis
Delete Kasowanie pliku/katalogu.
Refresh Odświerza dane w klasie o pliku/katalogu.
Jak juz mówilismy, po FileSystemInfo, dziedziczą:• FileInfo:
FileInfo jest klasa która pozwala na manipulacje plikiem.
![Page 8: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/8.jpg)
FileInfoWłaściwość Opis
Directory Zwraca DirectoryInfo dla ktalogu w którym znajduję sie plik.
DirectoryName Nazwa katalogu w którym znajduję sie plik
IsReadOnly Sprawdzenie lub przypisanie atrybutu read-only.
Length Rozmiar pliku
![Page 9: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/9.jpg)
FileInfoMetoda Opis
AppendText Tworzy StreamWriter który pozwala na dpisanie tektu do pliku.
CopyTo Tworzy kopie pliku w wybranej lokalizacji
Create Tworzy nowy plik
CreateText Tworzy nowy StreamWriter oraz nowy plik do zapisu.
Encrypt Szyfruje plik danego użytkownika
Decrypt Odszyfruje plik
MoveTo Przenosi plik w nowe miejsce. (Cut-Paste)
Open Otwiera plik z zestawem wybranych uprawnień
OpenRead Otwiera plik tylko do odczytu
OpenText Otwiera plik i zwraca StreamReader pozwalający na odczyt tekstu z pliku.
OpenWrite Otwiera plik tylko do zapisu
Replace Podmienia plik
![Page 10: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/10.jpg)
Jak odczytać informacje o pliku?Aby uzyskać informacje o konkretnym
pliku należy: Utworzyć nowy objekt FileInfo podając
ścieżkę dostępu do pliku. Reszta będzie już w utworzonym
obiekcie.
![Page 11: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/11.jpg)
Przykład:FileInfo ourFile = new FileInfo(@"c:\boot.ini "); if (ourFile.Exists) {
Console.WriteLine("Filename : {0}",ourFile.Name); Console.WriteLine("Path : {0}",ourFile.FullName);
}
Kopiowanie?
FileInfo ourFile = new FileInfo(@"c:\boot.ini");ourFile.CopyTo(@"c:\boot.bak");
![Page 12: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/12.jpg)
DirectoryInfo
Jest to klasa która pozwala na manipulacje katalogiem.
Najważniejsze właściwości:
Właściwość Opis
Parent Zwraca objekt DirectoryInfo dla katalogu który zawiera nasz katalog (rodzica)
Root Zwraca bazowego rodzica (string)
![Page 13: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/13.jpg)
DirectoryInfo
Najważniejsze metody:Metoda Opis
Create Tworzy nowy katalog
CreateSubdirectory Tworzy nowy katalog ktorego rodzicem jest aktualny katalog
GetDirectories Zwraca tablice z katalogami w danym katalogu
GetFiles Zwraca tablice z plikami w danym katalogu
GetFileSysytemInfos Zwraca tablice z objektami FileSystemInfo dla kazdego pliku/katalogu w danym katalogu.
MoveTo Przenosi plik.
![Page 14: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/14.jpg)
Jak przeszukac pliki w katalogu? Tworzymy objekt DirectoryInfo wskazujacy
na katalog który chcemy przeszukać. Wywołujemy metodę GetFiles.Przykład:
DirectoryInfo ourDir = new DirectoryInfo(@"c:\windows");
Console.WriteLine("Directory: {0}", ourDir.FullName);
foreach (FileInfo file in ourDir.GetFiles()) {Console.WriteLine("File: {0}", file.Name);
}
![Page 15: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/15.jpg)
DriveFormat
DriveFormat pozwala na pozyskiwanie onformacji o dyskach.
Właściwość Opis
AvailableFreeSpace Ilość wolnego dostępnego miejsca na dysku.
DriveFormat Zwraca format dysku (NTFS, FAT32, etc..)
DriveType Typ dysku (opisane poźniej)
IsReady Sprawdza czy dysk jest gotowy do odczytu/zapisu
Name Nazwa dysku (literka)
RootDirectory Objekt DirectoryInfo dla tego dysku
TotalFreeSpace Całkowitą wolną powierzchnie na dysku
TotalSize Całkowity rozmiar dysku
VolumeLabel Nazwa dysku
![Page 16: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/16.jpg)
DriveInfo
Metody DriveFormat:GetDrives: metoda statyczna, zwraca
wszystkie dyski w komputerze.
DriveType to enumeracja opisująca typ dysku: CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, Unknown
![Page 17: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/17.jpg)
Jak odczytać dyski?
Wywołać statyczna metoda GetDrives. Iterować przez zwróconą tablice
DriveInfo.
DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives)
{ Console.WriteLine("Drive: {0}", drive.Name); Console.WriteLine("Type: {0}", drive.DriveType);
}
![Page 18: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/18.jpg)
Klasa Path Pozwala na manipulacje Ścieżkami Statyczne metody:
ChangeExtension Combine GetDirectoryName GetExtension GetFileName GetFileNameWIthoutExtension GetFillPath GetPathRoot GetRandomFileName GetTempFileName GetTempPath HasExtension IsPathRooted
![Page 19: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/19.jpg)
Jak zmienić rozszerzenie pliku?
string ourPath = @"c:\boot.ini";Console.WriteLine(ourPath); Console.WriteLine("Ext: {0}",
Path.GetExtension(ourPath));Console.WriteLine("Change Path: {0}",
Path.ChangeExtension(ourPath, "bak"));
![Page 20: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/20.jpg)
FileSystemWatcher
Pozwala monitorować system plików. Właściwości:
EnableRisingEventsFilterIncludeSubdirectoriesNotifyFilterPath
![Page 21: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/21.jpg)
Jak monitorować katalog? Otworzyć nowy FileSystemWatcher. Ustalić Path. Zapisać sie do eventów Creader i
Deleted. Włączyć eventy poprzez ustawienie
EnableRisingEvents na true.
![Page 22: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/22.jpg)
Przykład FileSystemWatcherFileSystemWatcher watcher = new
FileSystemWatcher(); watcher.Path = @"c:\"; watcher.Created += new
FileSystemEventHandler(watcher_Changed);
watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;
static void watcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine("Directory changed({0}): {1}",
e.ChangeType, e.FullPath);
}
![Page 23: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/23.jpg)
Lab:Przeszukiwanie plików i ich monitorowanie. Na tym Lab, przeszukamy pliki i katalogi
w danym katalogu i bedziemy monitorowac czy jakikolwiek z tych plikow lub katalogów zmienił sie.
![Page 24: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/24.jpg)
Strumienie
Jest to sposob na prace z danymi w .NET Framework.
Wszystkie strumienie dziedzicza z abstrakcyjnej klasy Stream.
Klasa stream zawiera właściwości takie jak: CanRead, CanSeek, CanTimeout, CanWrite, Length, Position, ReadTimeout, WriteTimeout.
![Page 25: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/25.jpg)
Strumienie
Klasa Stream posiada metody takie jak: Close, Flush, Read, ReadByte, Seek, SetLength, Write, WriteByte.
Klasy które dziedziczą po klasie Stream to miedzy innymi: FileStream, MemoryStream, CryptoStream, NetworkStream, GZipStream.
![Page 26: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/26.jpg)
Jakie klasy pozwalaja na odczyt i zapis danych ? Wiekszość operacji na plikach zaczyna
sie od klasy File. Klasa File pozwala na:
Operacje zapisu i odczytu calego pliku,Otwieranie, tworzenie plików do odczytu.Otwieranie, tworzenie plików do zapisu.Proste operacje (File.Exists, File.Delete, ...)
![Page 27: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/27.jpg)
Strumienie – File Klasa do strumieniowego zapisu danych na
plikach nazywa sie FileStream. Klasa File posiada podstawowe operacje
do otwierania plików w FileStream do zapisu lub odczytu.
Metody statyczne w File: AppendAllText, AppendText, Copy, Create, CreateText, Move, Open, OpenRead, OpenText, ReadAllBytes, ReadAllLines, ReadAllText, WriteAllBytes, WriteAllLines, WriteAllText.
![Page 28: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/28.jpg)
Strumienie - Directory
Klasa Directory jest klasą statyczną. Posiada metody służące do manipulacji
katalogów takie jak: CreateDirectory, Delete, Exists, GetCreationTime, GetCurrentDirectory, GetDiretiries, GetDirectoryRoot, GetFiles, GetFileSystemEntries
![Page 29: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/29.jpg)
Strumienie
FileAccess, enumeracja która ustala poziom uprawnień potrzebnych do otwarcia pliku. (Read, Write, ReadWrite)
FileMode, enumeracja która ustala jak dany plik ma być otwarty. (Append, Create, CreateNew, Open, OpenOrCreate, Truncate).
![Page 30: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/30.jpg)
FileStream
Klasa FileStream otwiera pliki do zapisu lub odczytu.
Najważniejsze właściwości to te które dziedziczy po Stream w dodawtku do kilka innych takich jak: Handle, Name.
Najważniejsze metody to też te które dziedziczy po Stream w dodatku do: Lock, Unllock.
![Page 31: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/31.jpg)
StreamReader
Klasa StreamReader pozwala na udczyt danych ze Strumienia.
Najważniejsze właściwości to: BaseStream, CurrentEncoding, EndOfStream.
Najważniejsze metody to: Close, Peek, Read, ReadBlock, ReadLine, ReadToEnd.
![Page 32: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/32.jpg)
Jak czytać z pliku ?FileStream theFile = File.Open(@"C:\boot.ini",
FileMode.Open, FileAccess.Read);
Metoda File.Open() zwraca objekt FileStream z otwartym juz plikiem,Jednak używanie klasy FileStream bezposrednio czasem bywa niewygodne.Dlatego warto użyć klasy StreamReader.
StreamReader rdr = new StreamReader(theFile); Console.Write(rdr.ReadToEnd()); rdr.Close(); theFile.Close();
Na skróty:
Console.WriteLine(File.ReadAllText(@"C:\boot.ini"));
![Page 33: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/33.jpg)
StreamWriter
Pozwala na zapisywanie danych w strumieniu.
Najważniejsze właściwości to: AutoFlush, BaseStream, Encoding i NewLine.
Najważniejsze metody to: Close, Write i WriteLine.
![Page 34: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/34.jpg)
StreamWriterStreamWriter writer = new StreamWriter(theFile);writer.WriteLine("Hello"); writer.Close();theFile.Close();
StreamWriter writer =File.CreateText(@"c:\somefile.txt");
writer.WriteLine("Hello"); writer.Close();
Na skróty:File.WriteAllText(@"c:\somefile.txt", "Hello");
![Page 35: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/35.jpg)
AlternatywyStreamWriter writer = new StreamWriter(theFile);
StreamWriter writer =File.CreateText(@"c:\somefile.txt");
File.WriteAllText(@"c:\somefile.txt", "Hello");
theFile = File.Open(@"c:\somefile.txt", FileMode.Open, FileAccess.Write);
theFile = File.OpenWrite(@"c:\somefile.txt");
theFile = File.Open(@"c:\somefile.txt", FileMode.OpenOrCreate, FileAccess.Write);
![Page 36: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/36.jpg)
Reader i Writer
Klasy *Reader i *Writer maja za zadnie
ułatwić czytanie danych strumieniowych.
StreamReader dziedziczy po TextReader a
StreamWriter dziedziczy po TextWriter.
![Page 37: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/37.jpg)
Dane Binarne
Nie wszystkie dane są tekstowe. Do odczytu danych binarnych używamy
BinaryReader. Do zapisu danych binarnych używamy
BinaryWriter.
![Page 38: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/38.jpg)
Dane BinarnePrzykład (zapis):
FileStream newFile = File.Create(@"c:\somefile.bin");
BinaryWriter writer = new BinaryWriter(newFile); long number = 100; byte[] bytes = new byte[] { 10, 20, 50, 100 }; string s = "hunger"; writer.Write(number); writer.Write(bytes); writer.Write(s); writer.Close();
![Page 39: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/39.jpg)
Dane BinarnePrzykład (otczyt):
FileStream newFile = File.Open(@"c:\somefile.bin", FileMode.Open);
BinaryReader reader = new BinaryReader(newFile); long number = reader.ReadInt64(); byte[] bytes = reader.ReadBytes(4); string s = reader.ReadString(); reader.Close(); Console.WriteLine(number); foreach (byte b in bytes)
Console.Write("[{0}]", b); Console.WriteLine(); Console.WriteLine(s);
![Page 40: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/40.jpg)
Inne typy strumieni
MemoryStream – zapis i odczyt bezposrednio do pamięci RAM.
BufferedStream – poprawia czasem wydajność zapisu strumieni poprzez buforowanie danych.
![Page 41: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/41.jpg)
Kompresja danych
W .NET Framework, kompresja danych opiera się o Strumienie Kompresujące.
Strumienie kompresujące to: GZipStream i DeflateStream.
Dane które będziemy kompresować są limitowane do 4 GB.
![Page 42: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/42.jpg)
GZipStream
Klasa GZipStream pozwala na kompresję danych znajdujących się w innym strumieniu używając metody GZIP.
GZipStream dziedziczy po Stream.
![Page 43: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/43.jpg)
DeflateStream
Pozwala na kompresję danych używając metody Deflate.
Również bazuję na Stream.
![Page 44: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/44.jpg)
Jak kompresować dane?Kompresja w .NET bazuję na strumieniach, są to jednak innego
typu strumienie niż omawiane do tej pory. Strumienie kompresujące zapisuja skompresowane dane do innych strumieni.
Przykład:
FileStream sourceFile = File.OpenRead(inFilename);FileStream destFile = File.Create(outFilename); GZipStream compStream = new GZipStream(destFile,
CompressionMode.Compress);int theByte = sourceFile.ReadByte(); while (theByte != -1)
{ compStream.WriteByte((byte)theByte); theByte = sourceFile.ReadByte(); }
![Page 45: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/45.jpg)
Isolated Storage
Co to jest Isolated Storage? Klasa IsolatedStorageFile Rodzaje Isolated Storage Klasa IsolatedStorageFileStream
![Page 46: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/46.jpg)
Jak tworzyć Isolated Storage? Zdecydować jaki typ IS potrzebujemy.
IsolatedStorageFile machineStorage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFile userStorage = IsolatedStorageFile.GetUserStoreForAssembly();
![Page 47: PB.NET II (System.IO)](https://reader035.fdocuments.pl/reader035/viewer/2022081602/5483306eb4af9fdd658b475a/html5/thumbnails/47.jpg)
Czytanie i zapis do ISIsolatedStorageFile userStore =
IsolatedStorageFile.GetUserStoreForAssembly();
IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("UserSettings.set", FileMode.Create, userStore);
StreamWriter userWriter = new StreamWriter(userStream);
userWriter.WriteLine("User Prefs");userWriter.Close();
IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("UserSettings.set", FileMode.Open, userStore);