C# 文件与目录的基本操作(System.IO)

转载自:http://www.cnblogs.com/SkySoot/archive/2012/03/12/2391704.html

运行效果:

代码:

  1 /// <summary>
  2 /// 文件读写操作
  3 /// 为简化代码供大家学习,暂不考虑捕捉异常
  4 /// </summary>
  5 public partial class TestIO : DevComponents.DotNetBar.Office2007Form
  6 {
  7     public TestIO()
  8     {
  9         InitializeComponent();
 10     }
 11  
 12     /// <summary>
 13     /// 创建文件
 14     /// </summary>
 15     private void btnCreateFile_Click(object sender, EventArgs e)
 16     {
 17         string path = Application.StartupPath + @"Test.txt";
 18         FileStream fs = new FileStream(path, FileMode.Create);
 19         StreamWriter sw = new StreamWriter(fs);
 20         sw.WriteLine("This is a test file.");
 21         sw.WriteLine("This is second line.");
 22         sw.Close();
 23         fs.Close();
 24  
 25         // 也可以这样创建 StreamWriter
 26         // StreamWriter sw = File.CreateText(path);
 27     }
 28  
 29     /// <summary>
 30     /// 读取文件
 31     /// </summary>
 32     private void btnReadFile_Click(object sender, EventArgs e)
 33     {
 34         string path = Application.StartupPath + "\Test.txt";
 35         textBoxX1.Text = string.Empty;
 36         if (File.Exists(path))
 37         {
 38             FileStream fs = new FileStream(path, FileMode.Open);
 39             StreamReader sr = new StreamReader(fs);
 40             // 也可以这样创建 StreamReader
 41             // File.OpenText(path);
 42             string str = string.Empty;
 43             while (true)
 44             {
 45                 str = sr.ReadLine();
 46                 if (!string.IsNullOrEmpty(str))
 47                 {
 48                     textBoxX1.Text += str + "
";
 49                 }
 50                 else
 51                 {
 52                     sr.Close();
 53                     fs.Close();
 54                     break;
 55                 }
 56             }
 57         }
 58         else
 59         {
 60             MessageBox.Show("指定的路径下不存在此文件!");
 61         }
 62     }
 63  
 64     /// <summary>
 65     /// 追加文件内容
 66     /// </summary>
 67     private void btnAppendFile_Click(object sender, EventArgs e)
 68     {
 69         string path = Application.StartupPath + "\Test.txt";
 70         FileStream fs = new FileStream(path, FileMode.Append);
 71         StreamWriter sw = new StreamWriter(fs);
 72         // 也可以这样创建 StreamReader
 73         // StreamWriter sw = File.AppendText(path);
 74         sw.WriteLine("This is three line.");
 75         sw.Close();
 76         fs.Close();
 77     }
 78  
 79     /// <summary>
 80     /// 复制文件
 81     /// </summary>
 82     private void btnCopyFile_Click(object sender, EventArgs e)
 83     {
 84         string oldPath = Application.StartupPath + "\Test.txt";
 85         string newPath = Application.StartupPath + "\TestClone.txt";
 86         File.Copy(oldPath, newPath);
 87     }
 88  
 89     /// <summary>
 90     /// 删除文件
 91     /// </summary>
 92     private void btnDeleteFile_Click(object sender, EventArgs e)
 93     {
 94         string path = Application.StartupPath + "\TestClone.txt";
 95         File.Delete(path);
 96     }
 97  
 98  
 99     /// <summary>
100     /// 移动文件
101     /// </summary>
102     private void btnMoveFile_Click(object sender, EventArgs e)
103     {
104         string oldPath = Application.StartupPath + "\Test.txt";
105         // 移动文件的同时也可以使用新的文件名
106         string newPath = "d:\NewTest.txt";
107         File.Move(oldPath, newPath);
108     }
109  
110     /// <summary>
111     /// 创建目录
112     /// </summary>
113     private void btnCreateDirectory_Click(object sender, EventArgs e)
114     {
115         string path1 = "d:\Jason1";
116         // 创建目录 Jason1
117         DirectoryInfo dDepth1 = Directory.CreateDirectory(path1);
118         // dDepth2 指向 dDepth1 创建的子目录 Jason2
119         DirectoryInfo dDepth2 = dDepth1.CreateSubdirectory("Jason2");
120         // 设置应用程序当前的工作目录为 dDepth2 指向的目录
121         Directory.SetCurrentDirectory(dDepth2.FullName);
122         // 在当前目录创建目录 Jason3
123         Directory.CreateDirectory("Jason3");
124     }
125  
126     private void btnDeleteDirectory_Click(object sender, EventArgs e)
127     {
128         string path = "d:\Jason1";
129         DeleteDirectory(path);
130     }
131  
132     /// <summary>
133     /// 删除目录及其所有子目录,文件
134     /// </summary>
135     private static void DeleteDirectory(string path)
136     {
137         if (Directory.Exists(path))
138         {
139             foreach (string str in Directory.GetFileSystemEntries(path))
140             {
141                 if (File.Exists(str))
142                 {
143                     File.Delete(str);
144                 }
145                 else
146                 {
147                     DeleteDirectory(str);
148                 }
149             }
150             Directory.Delete(path);
151         }
152         else
153         {
154             MessageBox.Show("该目录不存在!");
155         }
156     }
157  
158     private void btnCopyDirectory_Click(object sender, EventArgs e)
159     {
160         string sourcePath = "d:\Jason1";
161         string targetPath = "d:\Jason2";
162         CopyDirectory(sourcePath, targetPath);
163     }
164  
165     /// <summary>
166     /// 复制目录及其所有内容
167     /// </summary>
168     /// <param name="sourcePath">源目录</param>
169     /// <param name="targetPath">目标目录</param>
170     private void CopyDirectory(string sourcePath, string targetPath)
171     {
172         // 该字符用于在反映分层文件系统组织的路径字符串中分隔目录级别(msdn)
173         // 在windows系统下实质上是为目录路径加上"\"
174         if (targetPath[targetPath.Length - 1] != Path.DirectorySeparatorChar)
175         {
176             targetPath += Path.DirectorySeparatorChar;
177         }
178         // 目标目录不存在则创建之
179         if (!Directory.Exists(targetPath))
180         {
181             Directory.CreateDirectory(targetPath);
182         }
183         // 获取文件系统(含目录和文件)
184         string[] fileList = Directory.GetFileSystemEntries(sourcePath);
185         foreach (string fileName in fileList)
186         {
187             if (Directory.Exists(fileName))
188             {
189                 // Path.GetFileName(fileName) 可取出最后一个分级目录名或文件名
190                 CopyDirectory(fileName, targetPath + Path.GetFileName(fileName));
191             }
192             else
193             {
194                 // true 为可覆盖
195                 File.Copy(fileName, targetPath + Path.GetFileName(fileName), true);
196             }
197         }
198     }
199 }
原文地址:https://www.cnblogs.com/KTblog/p/4450738.html