类库为文件操作提供了两个不同的类:File类和FileInfo类。其中,File类较为简单,是一个静态的方法集,用于操作整个文件。可以移动、复制、新建或删除文件。加入需要对文件内容或特性进行更为详细的访问,则应该使用FileInfo类,下面为File类的应用:
1
/*
2 Example15_3.cs illustrates the File class
3 */
4
5 using System;
6 using System.Windows.Forms;
7 using System.IO;
8
9 class Example15_3
10 {
11
12 public static void Main()
13 {
14
15 // create and show an open file dialog
16 OpenFileDialog dlgOpen = new OpenFileDialog();
17 if (dlgOpen.ShowDialog() == DialogResult.OK)
18 {
19 // use the File class to return info about the file
20 string s = dlgOpen.FileName;
21 Console.WriteLine( " Filename " + s);
22 Console.WriteLine( " Created at " + File.GetCreationTime(s));
23 Console.WriteLine( " Accessed at " +
24 File.GetLastAccessTime(s));
25 }
26
27 }
28
29 }
2 Example15_3.cs illustrates the File class
3 */
4
5 using System;
6 using System.Windows.Forms;
7 using System.IO;
8
9 class Example15_3
10 {
11
12 public static void Main()
13 {
14
15 // create and show an open file dialog
16 OpenFileDialog dlgOpen = new OpenFileDialog();
17 if (dlgOpen.ShowDialog() == DialogResult.OK)
18 {
19 // use the File class to return info about the file
20 string s = dlgOpen.FileName;
21 Console.WriteLine( " Filename " + s);
22 Console.WriteLine( " Created at " + File.GetCreationTime(s));
23 Console.WriteLine( " Accessed at " +
24 File.GetLastAccessTime(s));
25 }
26
27 }
28
29 }
下面是使用FileInfo类的例子:
1
/*
2 Example15_5.cs illustrates the FileInfo class
3 */
4
5 using System;
6 using System.Windows.Forms;
7 using System.IO;
8
9 class Example15_5
10 {
11
12 public static void Main()
13 {
14
15 // create and show an open file dialog
16 OpenFileDialog dlgOpen = new OpenFileDialog();
17 if (dlgOpen.ShowDialog() == DialogResult.OK)
18 {
19 // use the File class to return info about the file
20 FileInfo fi = new FileInfo(dlgOpen.FileName);
21 Console.WriteLine( " Filename " + fi.FullName );
22 Console.WriteLine( " Created at " + fi.CreationTime );
23 Console.WriteLine( " Accessed at " + fi.LastAccessTime );
24 }
25
26 }
27
28 }
2 Example15_5.cs illustrates the FileInfo class
3 */
4
5 using System;
6 using System.Windows.Forms;
7 using System.IO;
8
9 class Example15_5
10 {
11
12 public static void Main()
13 {
14
15 // create and show an open file dialog
16 OpenFileDialog dlgOpen = new OpenFileDialog();
17 if (dlgOpen.ShowDialog() == DialogResult.OK)
18 {
19 // use the File class to return info about the file
20 FileInfo fi = new FileInfo(dlgOpen.FileName);
21 Console.WriteLine( " Filename " + fi.FullName );
22 Console.WriteLine( " Created at " + fi.CreationTime );
23 Console.WriteLine( " Accessed at " + fi.LastAccessTime );
24 }
25
26 }
27
28 }