using System;
2 using System.IO;
3 class Test
4 {
5 public static void Main()
6 {
7 string path = @"c:\temp\123.txt";
8 if (!File.Exists(path))
9 {
10 // 创建文件以便写入内容。
11 using (StreamWriter sw = File.CreateText(path))
12 {
13 sw.WriteLine("Hello");
14 sw.WriteLine("And");
15 sw.WriteLine("Welcome");
16 }
17 }
18 // 打开文件从里面读数据。
19 using (StreamReader sr = File.OpenText(path))
20 {
21 string s = "";
22 while ((s = sr.ReadLine()) != null)
23 {
24 Console.WriteLine(s);
25 }
26 }
27 try
28 {
29 string path2 = path + "temp";
30 // 确认将要拷贝成的文件是否已经有同名的文件存在。
31 File.Delete(path2);
32 // 拷贝文件。
33 File.Copy(path, path2);
34 Console.WriteLine("{0} was copied to {1}.", path, path2);
35 // 删除新生成的文件。
36 File.Delete(path2);
37 Console.WriteLine("{0} was successfully deleted.", path2);
38 }
39 catch (Exception e)
40 {
41 Console.WriteLine("The process failed: {0}", e.ToString());
42 }
43 }
44 }