C# 文件操作总结

一、需求分析

  1.将信息记录到本地记事本中。

  2.将记录的信息读取出来。

  3.计算出某个文件夹下所有后缀名为txt的数量和dll的数量。

  4.从网络上下载文件。

二、二话不说上代码

 1 using System;
 2 using System.IO;
 3 using System.Text;
 4 
 5 namespace FileOperation
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             SaveLoginInfo();
12             ReadLoginInfo();
13             Ergodic();
14         }
15 
16 
17         /// <summary>
18         /// 本地文件中保存登录信息
19         /// </summary>
20         static void SaveLoginInfo()
21         {
22             #region 在本地保存登录信息
23             //判断文件是否存在
24             string loginDicPath = "E:\\Login";
25             if (!Directory.Exists(loginDicPath))
26             {
27                 Directory.CreateDirectory(loginDicPath);
28             }
29             string loginFilePath = loginDicPath + "\\login.txt";
30             //可以指定盘符,也可以指定任意文件名,还可以为word等文件
31             FileStream fs = new FileStream(loginFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
32             //创建写入流
33             StreamWriter sw = new StreamWriter(fs);
34             string testContent = "用户已登录";
35             sw.WriteLine(testContent);
36             sw.Close();
37             #endregion
38         }
39 
40         /// <summary>
41         /// 读取登录信息
42         /// </summary>
43         static void ReadLoginInfo()
44         {
45             string loginFilePath = "E:\\Login\\login.txt";
46             if (File.Exists(loginFilePath))
47             {
48                 StreamReader st = new StreamReader(loginFilePath, Encoding.UTF8);
49                 string content = st.ReadToEnd();
50                 st.Close();
51                 Console.WriteLine(content);
52             }
53         }
54 
55         /// <summary>
56         /// 遍历文件夹,计算文件夹中txt的数量和dll的数量
57         /// </summary>
58         static void Ergodic()
59         {
60             string loginDicPath = "E:\\testDic";
61             DirectoryInfo root = new DirectoryInfo(loginDicPath);
62             DirectoryInfo[] dics = root.GetDirectories();
63             int txtNum = 0;
64             int dllNum = 0;
65             foreach (DirectoryInfo info in dics)
66             {
67                 string path = info.FullName;
68                 //获取该文件夹下的所有文件
69                 DirectoryInfo root_Children = new DirectoryInfo(path);
70                 FileInfo[] filesChildren = root_Children.GetFiles();
71                 //获取完整路径名
72                 foreach (FileInfo fileInfo in filesChildren)
73                 {
74                     if (fileInfo.Extension == ".txt")
75                     {
76                         txtNum += 1;
77                     }
78                     else if (fileInfo.Extension == ".dll")
79                     {
80                         dllNum += 1;
81                     }
82                     else
83                     {
84                     }
85                 }
86             }
87             Console.WriteLine("txt的数量为{0},dll的数量为{1}", txtNum, dllNum);
88         }
89     }
90 }

注:对于需求3的目录结构如下

   

 需求4的代码(下载网络文件到本地)

 1 using System;
 2 using System.Linq;
 3 using System.Net;
 4 
 5 namespace FileOperation
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             DownloadWebFile();
12         }
13 
14 
15         /// <summary>
16         /// 下载网络文件
17         /// </summary>
18         static void DownloadWebFile()
19         {
20             //网络文件地址
21             string webFileUrl = "http://127.0.0.1:8088//error-file.txt";
22             //下载地址
23             string myDictionary = AppDomain.CurrentDomain.BaseDirectory;
24             //获取文件名称
25             string fileName = GetFileName(webFileUrl);
26             if (!HttpFileExist(webFileUrl))
27             {
28                 Console.WriteLine("服务器上没有该文件");
29                 return;
30             }
31             else
32             {
33                 WebClient client = new WebClient();
34                 client.DownloadFile(webFileUrl, myDictionary + "/" + fileName);
35             }
36 
37         }
38 
39         /// <summary>
40         /// 判断网络文件是否存在
41         /// </summary>
42         /// <param name="fileUrl"></param>
43         /// <returns></returns>
44         static bool HttpFileExist(string fileUrl)
45         {
46             try
47             {
48                 //创建根据网络地址的请求对象
49                 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(fileUrl));
50                 httpWebRequest.Method = "HEAD";
51                 httpWebRequest.Timeout = 1000;
52                 //返回响应状态是否是成功比较的布尔值
53                 using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
54                 {
55                     return response.StatusCode == HttpStatusCode.OK;
56                 }
57             }
58             catch (Exception ex)
59             {
60                 return false;
61             }
62         }
63 
64         /// <summary>
65         /// 获取文件名称
66         /// </summary>
67         /// <param name="url"></param>
68         /// <returns></returns>
69         private static string GetFileName(string url)
70         {
71             string fileName = "";
72             string[] str = url.Split('/');
73             fileName = str.Last();
74             return fileName;
75         }
76     }
77 }

三、写到后面的话

  其实这篇都算不上是文件操作汇总,我只是把新学到的知识放到了一个小小的项目中,以便自己后期用到能随时查询出来。C#对文件的操作不仅仅是这些,还有很多操作,就不一一列举验证。

继续加油~

posted @ 2019-03-05 22:11  雪球茸茸  阅读(404)  评论(0编辑  收藏  举报