- Implementing serialization and input/output functionality in a .NET Framework application (18 percent)
- Access files and folders by using the File System classes
- May include but is not limited to: File class and FileInfo class; Directory class and DirectoryInfo class;
- DriveInfo class and DriveType enumeration; FileSystemInfo class and FileSystemWatcher class; Path class;
- ErrorEventArgs class and ErrorEventHandler delegate; RenamedEventArgs class and RenamedEventHandler delegate
- Manage byte streams by using Stream classes
- May include but is not limited to: FileStream class; Stream class; MemoryStream; BufferedStream class
- Manage .NET Framework application data by using Reader and Writer classes
- May include but is not limited to: StringReader class and StringWriter class; TextReader class and TextWriter class;
- StreamReader class and Stream Writer class; BinaryReader class and BinaryWriter class
Il framework .NET offre numerose classi che permettono l'accesso al file system.
Di seguito riporto un pò di codice che utilizza tutte queste classi. Il loro utilizzo è molto intuitivo per questo non ritengo necessaria alcuna ulteriore spiegazione.
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Console.WriteLine("Drive\n");
6
7 DriveInfo driveInfo = new DriveInfo("C");
8 Console.WriteLine("Name: {0}", driveInfo.Name);
9 Console.WriteLine("TotalSize: {0} bytes", driveInfo.TotalSize);
10 Console.WriteLine("TotalFreeSpace: {0} bytes", driveInfo.TotalFreeSpace);
11 Console.WriteLine("AvailableFreeSpace: {0} bytes", driveInfo.AvailableFreeSpace);
12 Console.WriteLine("DriveFormat: {0}", driveInfo.DriveFormat);
13 Console.WriteLine("DriveType: {0}", driveInfo.DriveType);
14 Console.WriteLine("VolumeLabel: {0}", driveInfo.VolumeLabel);
15
16 Console.WriteLine("\nFile:\n");
17
18 File.AppendAllText("file1.txt", "Ciao a tutti da Andrea", Encoding.ASCII);
19 File.Copy("file1.txt", "file2.txt", true);
20
21 FileInfo file2Info = new FileInfo("file2.txt");
22 Console.WriteLine("CreationTime: {0}", file2Info.CreationTime);
23 Console.WriteLine("LastWriteTime: {0}", file2Info.LastWriteTime);
24 Console.WriteLine("DirectoryName: {0}", file2Info.DirectoryName);
25 Console.WriteLine("Exists: {0}", file2Info.Exists);
26 Console.WriteLine("Extension: {0}", file2Info.Extension);
27 Console.WriteLine("FullName: {0}", file2Info.FullName);
28 Console.WriteLine("Name: {0}", file2Info.Name);
29 Console.WriteLine("IsReadOnly: {0}", file2Info.IsReadOnly);
30 Console.WriteLine("Length: {0}", file2Info.Length);
31
32 Console.WriteLine("\nDirectory:\n");
33
34 DirectoryInfo dir2Info = file2Info.Directory;
35 Console.WriteLine("CreationTime: {0}", dir2Info.CreationTime);
36 Console.WriteLine("FullTime: {0}", dir2Info.FullName);
37 Console.WriteLine("Exists: {0}", dir2Info.Exists);
38 Console.WriteLine("LastAccessTime: {0}", dir2Info.LastAccessTime);
39 Console.WriteLine("LastWriteTime: {0}", dir2Info.LastWriteTime);
40
41 dir2Info.CreateSubdirectory("folder1");
42 dir2Info.CreateSubdirectory("folder2");
43 dir2Info.CreateSubdirectory("folder3");
44
45 Console.WriteLine("Files in folder: ");
46 foreach (FileInfo fileInfo in dir2Info.GetFiles())
47 {
48 Console.WriteLine("\t{0}", file2Info.Name);
49 }
50
51 Console.WriteLine("Directory in folder: ");
52 foreach (DirectoryInfo dirInfo in dir2Info.GetDirectories())
53 {
54 Console.WriteLine("\t{0}", dirInfo.Name);
55 }
56
57 if (Directory.Exists("folder1"))
58 {
59 Directory.Delete("folder1");
60 }
61 Directory.Delete("folder2");
62 new DirectoryInfo("folder3").Delete();
63 file2Info.Delete();
64
65 Console.WriteLine("\nPath: c:\\prova\\file.txt \n");
66 Console.WriteLine("GetDirectoryName: {0}", Path.GetDirectoryName(@"c:\prova\file.txt"));
67 Console.WriteLine("GetExtension: {0}", Path.GetExtension(@"c:\prova\file.txt"));
68 Console.WriteLine("GetFileName: {0}", Path.GetFileName(@"c:\prova\file.txt"));
69 Console.WriteLine("GetFileNameWithoutExtension: {0}", Path.GetFileNameWithoutExtension(@"c:\prova\file.txt"));
70 Console.WriteLine("GetFullPath: {0}", Path.GetFullPath(@"c:\prova\file.txt"));
71 Console.WriteLine("GetPathRoot: {0}", Path.GetPathRoot(@"c:\prova\file.txt"));
72 Console.WriteLine("GetRandomFileName: {0}", Path.GetRandomFileName());
73 Console.WriteLine("GetTempPath: {0}", Path.GetTempPath());
74 Console.WriteLine("GetTempFileName: {0}", Path.GetTempFileName());
75
76 Console.WriteLine("Combine: {0}", Path.Combine("c:\\prova1", "prova2\\file.txt"));
77
78 Console.WriteLine("\nFileSystemWatcher: \n");
79
80 Directory.CreateDirectory("folder");
81 FileSystemWatcher fsWatcher = new FileSystemWatcher("folder");
82 fsWatcher.Created += new FileSystemEventHandler(fsWatcher_Created);
83 fsWatcher.Deleted += new FileSystemEventHandler(fsWatcher_Deleted);
84 fsWatcher.Changed += new FileSystemEventHandler(fsWatcher_Changed);
85 fsWatcher.Renamed += new RenamedEventHandler(fsWatcher_Renamed);
86 fsWatcher.Error += new ErrorEventHandler(fsWatcher_Error);
87
88 fsWatcher.EnableRaisingEvents = true;
89
90 Console.ReadKey();
91 }
92
93 static void fsWatcher_Error(object sender, ErrorEventArgs e)
94 {
95 Console.WriteLine("FileSystemWatcher Error\n");
96 }
97
98 static void fsWatcher_Changed(object sender, FileSystemEventArgs e)
99 {
100 Console.WriteLine("ChangeType: {0}", e.ChangeType);
101 Console.WriteLine("FullPath: {0}", e.FullPath);
102 Console.WriteLine("Name: {0}\n", e.Name);
103 }
104
105 static void fsWatcher_Renamed(object sender, RenamedEventArgs e)
106 {
107 Console.WriteLine("ChangeType: {0}", e.ChangeType);
108 Console.WriteLine("FullPath: {0}", e.FullPath);
109 Console.WriteLine("Name: {0}", e.Name);
110 Console.WriteLine("OldFullPath: {0}", e.OldFullPath);
111 Console.WriteLine("OldName: {0}\n", e.OldName);
112 }
113
114 static void fsWatcher_Deleted(object sender, FileSystemEventArgs e)
115 {
116 Console.WriteLine("ChangeType: {0}", e.ChangeType);
117 Console.WriteLine("FullPath: {0}", e.FullPath);
118 Console.WriteLine("Name: {0}\n", e.Name);
119 }
120
121 static void fsWatcher_Created(object sender, FileSystemEventArgs e)
122 {
123 Console.WriteLine("ChangeType: {0}", e.ChangeType);
124 Console.WriteLine("FullPath: {0}", e.FullPath);
125 Console.WriteLine("Name: {0}\n", e.Name);
126 }
127 }
Gli stream realizzano un meccanismo unificato per gestire l'accesso sequenziale e random ai dati. La classe astratta Stream fornisce l'interfaccia di base e l'implementazione per tutti gli strem all'interno del Framework. Quando si apre un file viene restituito un oggetto di tipo FileStream che offre una interfaccia di basso livello per l'accesso al file. Le classi StreamReader e StreamWriter facilitano la lettura e la scrittura di file di testo. Le classi BinaryReader e BinaryWriter invece permettono la lettura e la scrittura di dati binari in modo più semplice del dover lavorare direttamente su vettori di byte.
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Console.WriteLine("*** Text Streams: ***\n");
6
7 FileStream fs = File.Open("file.txt", FileMode.Create);
8
9 byte[] bytesTitolo = new ASCIIEncoding().GetBytes("Titolo del file\r\n\r\n");
10 fs.Write(bytesTitolo, 0, bytesTitolo.Length);
11
12 using (StreamWriter sw = new StreamWriter(fs))
13 {
14 sw.WriteLine("Ciao a tutti");
15 sw.WriteLine("il mio nome è Andrea");
16 }
17
18 using (StreamReader sr = File.OpenText("file.txt"))
19 {
20 while (!sr.EndOfStream)
21 {
22 Console.WriteLine(sr.ReadLine());
23 }
24 }
25
26 Console.WriteLine();
27
28 File.WriteAllText("file2.txt", "Prima riga del file2\r\nSeconda riga del file2");
29 Console.WriteLine(File.ReadAllText("file2.txt"));
30
31 Console.WriteLine("\n*** Binary Streams: ***\n");
32
33 fs = File.Open("file3.dat", FileMode.Create);
34 using (BinaryWriter bw = new BinaryWriter(fs))
35 {
36 bw.Write('A');
37 bw.Write(true);
38 bw.Write(12.45);
39 bw.Write("Ciao");
40 }
41 fs = File.Open("file3.dat", FileMode.Open);
42 using (BinaryReader br = new BinaryReader(fs))
43 {
44 Console.WriteLine(br.ReadChar());
45 Console.WriteLine(br.ReadBoolean());
46 Console.WriteLine(br.ReadDouble());
47 Console.WriteLine(br.ReadString());
48 }
49
50 Console.WriteLine("\n*** Memory Streams: ***\n");
51
52 MemoryStream ms = new MemoryStream();
53 using (StreamWriter sw = new StreamWriter(ms))
54 {
55 sw.WriteLine("Scrivo su uno stream in memoria.");
56 sw.Flush();
57
58 using (fs = File.Open("file.txt", FileMode.Append))
59 {
60 ms.WriteTo(fs);
61 }
62 }
63
64 Console.ReadKey();
65 }
66 }