现在的位置: 首页 > 综合 > 正文

【类】C# 文件操作类(SamWang)

2012年08月31日 ⁄ 综合 ⁄ 共 8330字 ⁄ 字号 评论关闭

类库:

  1 /******************************************************************
  2  * 创 建 人:   SamWang
  3  * 创建时间:   2012-05-09
  4  * 描    述:
  5  *              C#文件操作类
  6  * 内容描述:   1.删除文件夹
  7  *              2.移动文件夹
  8  *              3.复制文件夹
  9  * 版    本:   V1.0 (2012-05-09)   
 10  * 修 改 人: 
 11  * 修改内容:
 12  * 版    本:
 13 ******************************************************************/
 14 using System;
 15 using System.IO;
 16 using System.Collections.Generic;
 17 
 18 namespace TestFileOperate
 19 {
 20     class FileOperate
 21     {      
 22         #region 文件操作
 23         /// <summary>
 24         /// 删除文件
 25         /// </summary>
 26         /// <param name="filePath"></param>
 27         public static void DeleteFile(string filePath)
 28         {
 29             if (File.Exists(filePath))
 30             {
 31                 File.Delete(filePath);
 32             }            
 33         }      
 34         
 35         #endregion
 36 
 37         #region 文件夹操作
 38         /// <summary>
 39         /// 复制文件夹中的所有文件夹与文件到另一个文件夹
 40         /// </summary>
 41         /// <param name="sourcePath">源文件夹</param>
 42         /// <param name="destPath">目标文件夹</param>
 43         public static void CopyFolder(string sourcePath,string destPath)
 44         {
 45             if (Directory.Exists(sourcePath))
 46             {
 47                 if (!Directory.Exists(destPath))
 48                 {
 49                     //目标目录不存在则创建
 50                     try
 51                     {
 52                         Directory.CreateDirectory(destPath);
 53                     }
 54                     catch (Exception ex)
 55                     {
 56                         throw new Exception("创建目标目录失败:" + ex.Message);
 57                     }
 58                 }
 59                 //获得源文件下所有文件
 60                 List<string> files = new List<string>(Directory.GetFiles(sourcePath));                
 61                 files.ForEach(c =>
 62                 {         
 63                     string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
 64                     File.Copy(c, destFile,true);//覆盖模式
 65                 });
 66                 //获得源文件下所有目录文件
 67                 List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));                
 68                 folders.ForEach(c =>
 69                 {
 70                     string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
 71                     //采用递归的方法实现
 72                     CopyFolder(c, destDir);
 73                 });                
 74             }
 75             else
 76             {
 77                 throw new DirectoryNotFoundException("源目录不存在!");
 78             }            
 79         }
 80 
 81         /// <summary>
 82         /// 移动文件夹中的所有文件夹与文件到另一个文件夹
 83         /// </summary>
 84         /// <param name="sourcePath">源文件夹</param>
 85         /// <param name="destPath">目标文件夹</param>
 86         public static void MoveFolder(string sourcePath, string destPath)
 87         {
 88             if (Directory.Exists(sourcePath))
 89             {
 90                 if (!Directory.Exists(destPath))
 91                 {
 92                     //目标目录不存在则创建
 93                     try
 94                     {
 95                         Directory.CreateDirectory(destPath);
 96                     }
 97                     catch (Exception ex)
 98                     {
 99                         throw new Exception("创建目标目录失败:" + ex.Message);
100                     }
101                 }
102                 //获得源文件下所有文件
103                 List<string> files = new List<string>(Directory.GetFiles(sourcePath));
104                 files.ForEach(c =>
105                 {
106                     string destFile = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
107                     //覆盖模式
108                     if (File.Exists(destFile))
109                     {
110                         File.Delete(destFile);
111                     }
112                     File.Move(c, destFile);
113                 });
114                 //获得源文件下所有目录文件
115                 List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
116 
117                 folders.ForEach(c =>
118                 {
119                     string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
120                     //Directory.Move必须要在同一个根目录下移动才有效,不能在不同卷中移动。
121                     //Directory.Move(c, destDir);
122 
123                     //采用递归的方法实现
124                     MoveFolder(c, destDir);
125                 });
126             }
127             else
128             {
129                 throw new DirectoryNotFoundException("源目录不存在!");
130             }
131         }
132 
133         #region 删除指定目录下所有内容
134         /// <summary>
135         /// 删除指定目录下所有内容:方法一--删除目录,再创建空目录
136         /// </summary>
137         /// <param name="dirPath"></param>
138         public static void DeleteFolderEx(string dirPath)
139         {
140             if (Directory.Exists(dirPath))
141             {
142                 Directory.Delete(dirPath);
143                 Directory.CreateDirectory(dirPath);
144             }
145         }
146 
147         /// <summary>
148         /// 删除指定目录下所有内容:方法二--找到所有文件和子文件夹删除
149         /// </summary>
150         /// <param name="dirPath"></param>
151         public static void DeleteFolder(string dirPath)
152         {
153             if (Directory.Exists(dirPath))
154             {
155                 foreach (string content in Directory.GetFileSystemEntries(dirPath))
156                 {
157                     if (Directory.Exists(content))
158                     {
159                         Directory.Delete(content, true);
160                     }
161                     else if (File.Exists(content))
162                     {
163                         File.Delete(content);
164                     }
165                 }
166             }
167         }
168         #endregion
169         #endregion        
170     }
171 }

 

测试:

  1 /******************************************************************
  2  * 创 建 人:  SamWang
  3  * 创建时间:  2012-5-9 16:59
  4  * 描    述:
  5  *             用于测试文件操作
  6  * 版    本:  V1.0      
  7  * 修 改 人: 
  8  * 修改内容:
  9  * 版    本:
 10 ******************************************************************/
 11 using System;
 12 using System.Collections.Generic;
 13 using System.Linq;
 14 using System.Text;
 15 using System.IO;
 16 
 17 namespace TestFileOperate
 18 {
 19     class Program
 20     {
 21         static void Main(string[] args)
 22         {
 23             string dirPath = @"D:\TestDir";
 24             string filePath = @"D:\TestDir\TestFile.txt";
 25             //创建文件夹 
 26             Directory.CreateDirectory(dirPath);
 27             //创建文件
 28             using (File.Create(@"D:\TestDir\TestFile.txt")) ;
 29             //删除文件
 30             if (File.Exists(filePath))
 31             {
 32                 File.Delete(filePath);
 33             }
 34             //删除文件夹
 35             //Directory.Delete(dirPath); //删除空目录,否则需捕获指定异常处理
 36             Directory.Delete(dirPath, true);//删除该目录以及其所有内容
 37 
 38             #region 删除指定目录下所有文件夹和文件
 39             #region 准备数据
 40             Directory.CreateDirectory(dirPath);
 41             using (File.Create(dirPath + @"\test001.txt")) ;
 42             Directory.CreateDirectory(dirPath + @"\TestDir001");
 43             using (File.Create(dirPath + @"\TestDir001\test002.txt")) ;
 44             #endregion
 45             FileOperte.DeleteFolder(dirPath);
 46             #endregion
 47 
 48             #region 写入文件
 49             Console.WriteLine("<<<<<<<<<<<{0}>>>>>>>>>>", "WriteFile");
 50 
 51             //WriteAllLines
 52             File.WriteAllLines(filePath, new string[] { "11111", "22222", "3333" });
 53             File.Delete(filePath);
 54 
 55             //WriteAllText
 56             File.WriteAllText(filePath, "11111\r\n22222\r\n3333\r\n");
 57             File.Delete(filePath);
 58 
 59             //StreamWriter
 60             using (StreamWriter sw = new StreamWriter(filePath))
 61             {
 62                 sw.Write("11111\r\n22222\r\n3333\r\n");
 63                 sw.Flush();
 64             }
 65             #endregion
 66 
 67             #region 读取文件
 68             Console.WriteLine("<<<<<<<<<<<{0}>>>>>>>>>>", "ReadFile");
 69             //ReadAllLines
 70             Console.WriteLine("--{0}", "ReadAllLines");
 71             List<string> list = new List<string>(File.ReadAllLines(filePath));
 72             list.ForEach(str =>
 73             {
 74                 Console.WriteLine(str);
 75             });
 76 
 77             //ReadAllText
 78             Console.WriteLine("--{0}", "ReadAllLines");
 79             string fileContent = File.ReadAllText(filePath);
 80             Console.WriteLine(fileContent);
 81 
 82             //StreamReader
 83             Console.WriteLine("--{0}", "StreamReader");
 84             using (StreamReader sr = new StreamReader(filePath))
 85             {
 86                 //方法一:从流的当前位置到末尾读取流
 87                 fileContent = string.Empty;
 88                 fileContent = sr.ReadToEnd();
 89                 Console.WriteLine(fileContent);
 90                 //方法二:一行行读取直至为NULL
 91                 fileContent = string.Empty;
 92                 string strLine = string.Empty;
 93                 while (strLine != null)
 94                 {
 95                     strLine = sr.ReadLine();
 96                     fileContent += strLine + "\r\n";
 97                 }
 98                 Console.WriteLine(fileContent);
 99             }
100 
101             #endregion
102 
103             #region 文件路径
104             dirPath = @"D:\TestDir";
105             filePath = @"D:\TestDir\TestFile.txt";
106             Console.WriteLine("<<<<<<<<<<<{0}>>>>>>>>>>", "文件路径");
107             //获得当前路径
108             Console.WriteLine(Environment.CurrentDirectory);
109             //文件或文件夹所在目录
110             Console.WriteLine(Path.GetDirectoryName(filePath));     //D:\TestDir
111             Console.WriteLine(Path.GetDirectoryName(dirPath));      //D:\
112             //文件扩展名
113             Console.WriteLine(Path.GetExtension(filePath));         //.txt
114             //文件名
115             Console.WriteLine(Path.GetFileName(filePath));          //TestFile.txt
116             Console.WriteLine(Path.GetFileName(dirPath));           //TestDir
117             Console.WriteLine(Path.GetFileNameWithoutExtension(filePath)); //TestFile
118             //绝对路径
119             Console.WriteLine(Path.GetFullPath(filePath));          //D:\TestDir\TestFile.txt
120             Console.WriteLine(Path.GetFullPath(dirPath));           //D:\TestDir  
121             //更改扩展名
122             Console.WriteLine(Path.ChangeExtension(filePath, ".jpg"));//D:\TestDir\TestFile.jpg
123             //根目录
124             Console.WriteLine(Path.GetPathRoot(dirPath));           //D:\      
125             //生成路径
126             Console.WriteLine(Path.Combine(new string[] { @"D:\", "BaseDir", "SubDir", "TestFile.txt" })); //D:\BaseDir\SubDir\TestFile.txt
127             //生成随即文件夹名或文件名
128             Console.WriteLine(Path.GetRandomFileName());
129             //创建磁盘上唯一命名的零字节的临时文件并返回该文件的完整路径
130             Console.WriteLine(Path.GetTempFileName());
131             //返回当前系统的临时文件夹的路径
132             Console.WriteLine(Path.GetTempPath());
133             //文件名中无效字符
134             Console.WriteLine(Path.GetInvalidFileNameChars());
135             //路径中无效字符
136             Console.WriteLine(Path.GetInvalidPathChars());           
137 
138             #endregion
139 
140             #region 文件加解密
141             #region 数据准备
142             //File.WriteAllLines(filePath, new string[] { "11111", "22222", "3333" });
143             File.Encrypt(filePath);
144             Console.WriteLine(File.ReadAllText(filePath));
145             #endregion
146             
147             #endregion
148 
149             #region 文件属性
150             Console.WriteLine("<<<<<<<<<<<{0}>>>>>>>>>>", "文件属性");
151 
152             //use File class
153             Console.WriteLine(File.GetAttributes(filePath));
154             File.SetAttributes(filePath,FileAttributes.Hidden | FileAttributes.ReadOnly);
155             Console.WriteLine(File.GetAttributes(filePath));
156 
157             //user FilInfo class
158             FileInfo fi = new FileInfo(filePath);
159             Console.WriteLine(fi.Attributes.ToString());
160             fi.Attributes = FileAttributes.Hidden | FileAttributes.ReadOnly; //隐藏与只读
161             Console.WriteLine(fi.Attributes.ToString());
162 
163             //只读与系统属性,删除时会提示拒绝访问
164             fi.Attributes = FileAttributes.Archive;
165             Console.WriteLine(fi.Attributes.ToString());
166             #endregion
167 
168             #region 文件移动
169             #region 准备数据
170             Directory.CreateDirectory(dirPath);
171             using (File.Create(dirPath + @"\test001.txt")) ;
172             Directory.CreateDirectory(dirPath + @"\TestDir001");
173             using (File.Create(dirPath + @"\TestDir001\test002.txt")) ;
174             #endregion
175             //拷贝文件夹
176             FileOperte.CopyFolder(dirPath, @"C:\Test");
177             //移动文件夹中的所有文件夹与文件到另一个文件夹
178             FileOperte.MoveFolder(dirPath, @"C:\Test");         
179             #endregion
180         }
181     }
182 }

 

 

作者:SamWang
出处:http://wangshenhe.cnblogs.com/
本文版权归作者和博客园共有,欢迎围观转载。转载时请您务必在文章明显位置给出原文链接,谢谢您的合作。

 

抱歉!评论已关闭.