C#File类常用文件操作以及一个模拟的控制台文件管理系统

重温一下C#中File类的一些基本操作:

File类,是一个静态类,主要是来提供一些函数库用的。

使用时需要引入System.IO命名空间。

一、常用操作:

1、创建文件方法

//参数1:要创建的文件路径

File.Create@"D:TestDebug1测试.txt"

2、打开文件方法

 //参数1:要打开的文件路径,参数2:打开的文件方式

File.Open(@"D:TestDebug1测试.txt",FileMode.Append)

3、追加文件方法

 //参数1:要追加的文件路径,参数2:追加的内容

File.AppendAllText(@"D:TestDebug1测试.txt","哈哈");

4、复制文件方法

 //参数1:要复制的源文件路径,参数2:复制后的目标文件路径,参数3:是否覆盖相同文件名
 File.Copy(@"D:TestDebug1测试.txt", @"D:TestDebug2测试1.txt", true);

5、移动文件方法

 //参数1:要移动的源文件路径,参数2:移动后的目标文件路径
File.Move(@"D:TestDebug1测试.txt", @"D:TestDebug3测试2.txt");

6、删除文件方法

 //参数1:要删除的文件路径
 File.Delete(@"D:TestDebug1测试.txt");

7、设置文件属性方法

//参数1:要设置属性的文件路径,参数2:设置的属性类型(只读、隐藏等)
File.SetAttributes(@"D:TestDebug1测试.txt", FileAttributes.Hidden);

二、读写操作:

当读取的文件内容不多时:

  • File.ReadAllText(FilePath)
  • File.ReadAllText(FilePath, Encoding)
  • File.ReadAllLines(FilePath)

例如:

  • string str = File.ReadAllText(@"c: empascii.txt");
  • string str2 = File.ReadAllText(@"c: empascii.txt", Encoding.ASCII);
  • string[] strs = File.ReadAllLines(@"c: empascii.txt"); 

读取内容比较多时:使用StreamReader类

初始化:

  • StreamReader sr1 = new StreamReader(@"c: emputf-8.txt"); 
  • StreamReader sr2 = new StreamReader(@"c: emputf-8.txt", Encoding.UTF8);
  • FileStream fs = new FileStream(@"C: emputf-8.txt", FileMode.Open, FileAccess.Read, FileShare.None); 
  • StreamReader sr3 = new StreamReader(fs); 
  • StreamReader sr4 = new StreamReader(fs, Encoding.UTF8);

初始化后:

读一行 

  • string nextLine = sr.ReadLine();

读一个字符 

  • int nextChar = sr.Read();

读100个字符 

  • int nChars = 100; 
  • char[] charArray = new char[nChars]; 
  • int nCharsRead = sr.Read(charArray, 0, nChars);      

全部读完 

  • string restOfStream = sr.ReadToEnd();

使用完StreamReader之后,不要忘记关闭它:

  • sr.Closee();

写的内容不多时候

  • string str1 = "Good Morning!";
  • File.WriteAllText(@"c: emp estascii.txt", str1);
  • string[] strs = { "Good Morning!", "Good Afternoon!" };
  • File.WriteAllLines(@"c: empascii.txt", strs);

写的内容比较多时使用StreamWriter

如果文件不存在,创建文件; 如果存在,覆盖文件 

  • StreamWriter sw1 = new StreamWriter(@"c: emputf-8.txt"); 
  • FileStream fs = new FileStream(@"C: emputf-8.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read); 
  • StreamWriter sw3 = new StreamWriter(fs); 

如果文件不存在,创建文件; 如果存在,覆盖文件 

  • FileInfo myFile = new FileInfo(@"C: emputf-8.txt"); 
  • StreamWriter sw5 = myFile.CreateText();

初始化完成后,可以用StreamWriter对象一次写入一行,一个字符,一个字符数组,甚至一个字符数组的一部分。

写一个字符            

  • sw.Write('a');

写一个字符数组 

  • char[] charArray = new char[100];
  • sw.Write(charArray);

写一个字符数组的一部分 

  • sw.Write(charArray, 10, 15);

同样,StreamWriter对象使用完后,不要忘记关闭。

  • sw.Close();

=================================================================

接下来是一个简单的控制台应用程序的源码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using System.IO;
  7 
  8 namespace _033_test
  9 {
 10     class Program
 11     {
 12         static void Main(string[] args)
 13         {
 14             FileManager file = new FileManager();
 15             file.MenuChoice();
 16 
 17             Console.ReadKey();
 18         }
 19     }
 20 
 21     class FileManager
 22     {
 23         public void DisPlayer()
 24         {
 25             Console.WriteLine("============File Management System=============");
 26             Console.WriteLine("1.Create     2.Delete      3.Check     4.Revise");
 27             Console.WriteLine("===============================================");
 28             Console.WriteLine("请输入你要进行的操作编号,中途如要返回上一级请输入exit");
 29         }
 30 
 31         public void MenuChoice()
 32         {
 33             while (true)
 34             {
 35                 DisPlayer();
 36                 string choice = Console.ReadLine();
 37                 switch (choice)
 38                 {
 39                     case "1": Create(); continue;
 40                     case "2": Delete(); continue;
 41                     case "3": Check(); continue;
 42                     case "4": Revise(); continue;
 43                     case "exit": return;
 44                     default: Console.WriteLine("请重新输入正确的选项"); break;
 45                 }
 46             }
 47         }
 48 
 49         public void Create()
 50         {
 51             Console.WriteLine("请指定路径:");
 52             while (true)
 53             {
 54                 string path = Console.ReadLine();
 55                 if (path == "exit")
 56                 {
 57                     Console.WriteLine("返回上一级");
 58                     break;
 59                 }
 60                 try
 61                 {
 62                     if (File.Exists(path))
 63                     {
 64                         Console.WriteLine("是否覆盖原文件?Y/N");
 65                         string str = Console.ReadLine();
 66                         if (str == "y" || str == "Y")
 67                         {
 68                             File.Create(path).Close();
 69                             Console.WriteLine("已覆盖原文件");
 70                             break;
 71                         }
 72                         else
 73                         {
 74                             Console.WriteLine("放弃覆盖,请重新输入路径");
 75                             continue;
 76                         }
 77                     }
 78                     else
 79                     {
 80                         File.Create(path).Close();
 81                         Console.WriteLine("文件已创建");
 82                         break;
 83                     }
 84                 }
 85                 catch (Exception)
 86                 {
 87                     Console.WriteLine("错误路径,请重新输入");
 88                     continue;
 89                 }
 90             }
 91         }
 92 
 93         public void Delete()
 94         {
 95             Console.WriteLine("请指定路径:");
 96             while (true)
 97             {
 98                 string path = Console.ReadLine();
 99                 if (path == "exit")
100                 {
101                     Console.WriteLine("返回上一级");
102                     break;
103                 }
104                 if (File.Exists(path))
105                 {
106                     File.Delete(path);
107                     Console.WriteLine("文件已删除");
108                     break;
109                 }
110                 else
111                 {
112                     Console.WriteLine("不存在该文件,请重新输入路径");
113                     continue;
114                 }
115             }
116         }
117 
118         public void Check()
119         {
120             Console.WriteLine("请指定路径:");
121             while (true)
122             {
123                 string path = Console.ReadLine();
124                 if (path == "exit")
125                 {
126                     Console.WriteLine("返回上一级");
127                     break;
128                 }
129                 if (File.Exists(path))
130                 {
131                     FileInfo fInfo = new FileInfo(path);
132                     Console.WriteLine("1.查看文件信息  2.查看文件内容");
133                     while (true)
134                     {
135                         string str = Console.ReadLine();
136                         switch (str)
137                         {
138                             case "1":
139                                 Console.WriteLine("文件名:" + fInfo.Name);
140                                 Console.WriteLine("创建时间:" + fInfo.CreationTime);
141                                 Console.WriteLine("最后修改时间:" + fInfo.LastWriteTime);
142                                 Console.WriteLine("字节大小:" + fInfo.Length);
143                                 break;
144                             case "2":
145                                 string type = Path.GetExtension(path);
146                                 if (type == ".doc" || type == ".txt")
147                                 {
148                                     byte[] brr = File.ReadAllBytes(path);
149                                     string value = Encoding.Default.GetString(brr, 0, brr.Length);
150                                     Console.WriteLine(value);
151                                 }
152                                 else
153                                 {
154                                     Console.WriteLine("该类型文件不支持查看");
155                                 }
156                                 break;
157                             default: Console.WriteLine("错误指令,请重新输入:"); continue;
158                         }
159                         break;
160                     }
161                     break;
162                 }
163                 else
164                 {
165                     Console.WriteLine("不存在该文件,请重新输入路径");
166                     continue;
167                 }
168             }
169         }
170 
171         public void Revise()
172         {
173             Console.WriteLine("请指定路径:");
174             while (true)
175             {
176                 string path = Console.ReadLine();
177                 if (path == "exit")
178                 {
179                     Console.WriteLine("返回上一级");
180                     break;
181                 }
182                 if (File.Exists(path))
183                 {
184                     Console.WriteLine("1.修改内容  2.修改文件名  3.文末添加");
185                     while (true)
186                     {
187                         string str = Console.ReadLine();
188                         switch (str)
189                         {
190                             case "1":
191                                 Console.WriteLine("本功能允许你将某个字符串替换成另一个字符");
192                                 string type = Path.GetExtension(path);
193                                 if (type == ".doc" || type == ".txt")
194                                 {
195                                     byte[] brr = File.ReadAllBytes(path);
196                                     string value = Encoding.Default.GetString(brr, 0, brr.Length);
197                                     Console.WriteLine("请输入你要修改的字符串,若文件中有该字符,将全部替换");
198                                     string str2 = Console.ReadLine();
199                                     Console.WriteLine("请输入将要修改为的字符串");
200                                     string str3 = Console.ReadLine();
201                                     byte[] brr2 = Encoding.Default.GetBytes(value.Replace(str2, str3));
202                                     File.WriteAllBytes(path, brr2);
203                                 }
204                                 else
205                                 {
206                                     Console.WriteLine("该类型文件不支持修改");
207                                 }
208                                 break;
209                             case "2":
210                                 FileInfo f = new FileInfo(path);
211                                 while (true)
212                                 {
213                                     try
214                                     {
215                                         Console.WriteLine("请输入文件名(不需要输入拓展名和路径)");
216                                         string fName = Console.ReadLine();
217                                         //获取文件的父目录和拓展名,并加在fname两边,使其做到重命名的效果
218                                         File.Move(path, f.Directory + "\" + fName + Path.GetExtension(path));
219                                         Console.WriteLine("已将该文件重命名");
220                                     }
221                                     catch (Exception) {
222                                         Console.WriteLine("文件名出错,重新输入!");
223                                         continue;
224                                     }
225                                     break;
226                                 }
227                                 break;
228                             case "3":
229                                 Console.WriteLine("请输入内容,回车换行,exit退出");
230                                 FileStream fs = new FileStream(path, FileMode.Append);
231                                 while (true)
232                                 {
233                                     string value = Console.ReadLine();
234                                     if (value == "exit") break;
235                                     byte[] arr = Encoding.Default.GetBytes(value + "
");
236                                     fs.Write(arr, 0, arr.Length);
237                                     fs.Flush();
238                                 }
239                                 fs.Close();
240                                 break;
241                             default: Console.WriteLine("错误指令,请重新输入:"); continue;
242                         }
243                         break;
244                     }
245                     break;
246                 }
247                 else
248                 {
249                     Console.WriteLine("不存在该文件,请重新输入路径");
250                     continue;
251                 }
252             }
253         }
254     }
255 
256 
257 }
FileManager

运行结果:

参考来源:https://www.cnblogs.com/xielong/p/6187308.htmlhttps://www.cnblogs.com/Herzog3/p/5090974.html

原文地址:https://www.cnblogs.com/wq-KingStrong/p/10272728.html