c#之文件操作
1、c#文件操作涉及到的命名空间
using System.Text;
using System.IO;
2、路径输入
在上一篇中写到c#格式化输出,这里提一下获取控制台输入。
其实了解一点英语的朋友都知道Write是写那对着的Read是读,针对的对象是控制台。
我们常用的Console.WriteLine是写且带回车,则Console.ReadLine是从用户输入的地方开始读取直到该行结束。
Console.Write是一个字符一个字符的写,则Console.Read是从用户输入的地方开始一个字符一个字符的读取。
用户输入时“\”不用转义。
3、获取文件句柄
利用DirectoryInfo返回目录句柄,虽然目录是一种特殊的文件,但是这里的参数是目录路径不是文件路径。
后再通过该对象的GetFiles方法返回该目录下的文件信息或句柄。
4、读取文件内容
使用StreamReader在内存中开辟一个输入流,将磁盘文件读入到内存中。
然后通过该输入流对象的ReadLine方法读取文件,然后一行一行的输出。
注意:最后需要关闭输入流。
5、写文件
使用FileStream类创建文件,使用StreamWriter类,将数据写入到文件。
注意:最后需要清空缓存,关闭输出流。
示例:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.IO;
5
6 /// <summary>
7 /// [功能描述:
8 /// 1、使用 I/O 类列出某一目录下的所有文件名,并输出到标准控制台
9 /// 2、读文本文件(逐行),并输出到标准控制台
10 /// 3、新建一个文件并向文件中写入字符串
11 /// ]<br></br>
12 /// [创 建 者: XXX]<br></br>
13 /// [创建时间: 2017-08-28]<br></br>
14 /// <修改记录
15 /// 修改人=''
16 /// 修改时间='yyyy-mm-dd'
17 /// 修改目的=''
18 /// 修改描述=''
19 /// />
20 /// </summary>
21 namespace ConsoleApplication1
22 {
23 class File
24 {
25 public File()
26 {
27 Console.Write("请输入目录路路径:");
28 string path = Console.ReadLine();
29 ReadFileName(path);
30 Console.WriteLine();
31 Console.Write("请输入要读取的文件(默认为路径为上面的路径):");
32 path += "\\";
33 string path1 = path + Console.ReadLine();
34 ReadFileToConsole(path1);
35 Console.WriteLine();
36 Console.Write("请输入要写入的文件(默认为路径和内容分别为上面的路径和内容):");
37 string path2 = path + Console.ReadLine();
38 WriteFile(path1, path2);
39 }
40
41 /// <summary>
42 /// 说明:读取本地文件名
43 /// </summary>
44 /// <param name="path">目录路径</param>
45 /// <returns></returns>
46 /// <remarks>2017-08-28</remarks>
47 private void ReadFileName(string path)
48 {
49 DirectoryInfo dir = new DirectoryInfo(path);
50 FileInfo[] inf = dir.GetFiles();
51 foreach (FileInfo finf in inf)
52 {
53 Console.WriteLine(finf);
54 }
55 }
56
57 /// <summary>
58 /// 说明:读取本地文件内容到控制台
59 /// </summary>
60 /// <param name="path">文件路径</param>
61 /// <returns></returns>
62 /// <remarks>2017-08-28</remarks>
63 private void ReadFileToConsole(string path)
64 {
65 StreamReader sr = new StreamReader(path, Encoding.Default);
66 String line = null;
67 while ((line = sr.ReadLine()) != null)
68 {
69 Console.WriteLine(line.ToString());
70 }
71
72 //关闭流
73 sr.Close();
74 }
75
76 /// <summary>
77 /// 说明:读取本地文件内容写到另一文件中
78 /// </summary>
79 /// <param name="path">文件路径</param>
80 /// <returns></returns>
81 /// <remarks>2017-08-28</remarks>
82 private void WriteFile(string path1, string path2)
83 {
84 StreamReader sr = new StreamReader(path1, Encoding.Default);
85 FileStream fs = new FileStream(path2, FileMode.Create);
86 StreamWriter sw = new StreamWriter(fs);
87 String line = null;
88 while ((line = sr.ReadLine()) != null)
89 {
90 sw.Write(line.ToString());
91 }
92
93 //清空缓冲区
94 sw.Flush();
95
96 //关闭流
97 sw.Close();
98 sr.Close();
99 fs.Close();
100 }
101 }
102 }
结果: