原文连接:http://www.cnblogs.com/wangshenhe/archive/2012/05/09/2490438.html

文件与文件夹操作主要用到以下几个类:

  1.File类:  

提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建 FileStream 对象。

    msdn:http://msdn.microsoft.com/zh-cn/library/system.io.file(v=VS.80).aspx

  2.FileInfo类:

    提供创建、复制、删除、移动和打开文件的实例方法,并且帮助创建 FileStream 对象

    msdn:http://msdn.microsoft.com/zh-cn/library/system.io.fileinfo(v=VS.80).aspx

  3.Directory类:

    公开用于创建、移动和枚举通过目录和子目录的静态方法。

    msdn:http://msdn.microsoft.com/zh-cn/library/system.io.directory.aspx

  4.DirectoryInfo类:

    公开用于创建、移动和枚举目录和子目录的实例方法。

    msdn:http://msdn.microsoft.com/zh-cn/library/system.io.directoryinfo.aspx

  (注:以下出现的dirPath表示文件夹路径,filePath表示文件路径)

1.创建文件夹  

Directory.CreateDirectory(@"D:\TestDir");

2.创建文件

  创建文件会出现文件被访问,以至于无法删除以及编辑。建议用上using。

using (File.Create(@"D:\TestDir\TestFile.txt"));

3.删除文件
  删除文件时,最好先判断该文件是否存在!

if (File.Exists(filePath))
{
File.Delete(filePath);
}

4.删除文件夹

  删除文件夹需要对异常进行处理。可捕获指定的异常。msdn:http://msdn.microsoft.com/zh-cn/library/62t64db3(v=VS.80).aspx

Directory.Delete(dirPath); //删除空目录,否则需捕获指定异常处理
Directory.Delete(dirPath, true);//删除该目录以及其所有内容

5.删除指定目录下所有的文件和文件夹

  一般有两种方法:1.删除目录后,创建空目录 2.找出下层文件和文件夹路径迭代删除

 1         /// <summary>
2 /// 删除指定目录下所有内容:方法一--删除目录,再创建空目录
3 /// </summary>
4 /// <param name="dirPath"></param>
5 public static void DeleteDirectoryContentEx(string dirPath)
6 {
7 if (Directory.Exists(dirPath))
8 {
9 Directory.Delete(dirPath);
10 Directory.CreateDirectory(dirPath);
11 }
12 }
13
14 /// <summary>
15 /// 删除指定目录下所有内容:方法二--找到所有文件和子文件夹删除
16 /// </summary>
17 /// <param name="dirPath"></param>
18 public static void DeleteDirectoryContent(string dirPath)
19 {
20 if (Directory.Exists(dirPath))
21 {
22 foreach (string content in Directory.GetFileSystemEntries(dirPath))
23 {
24 if (Directory.Exists(content))
25 {
26 Directory.Delete(content, true);
27 }
28 else if (File.Exists(content))
29 {
30 File.Delete(content);
31 }
32 }
33 }
34 }

6.读取文件

  读取文件方法很多,File类已经封装了四种:

  一、直接使用File类

    1.public static string ReadAllText(string path); 

    2.public static string[] ReadAllLines(string path);

    3.public static IEnumerable<string> ReadLines(string path);

    4.public static byte[] ReadAllBytes(string path);

    以上获得内容是一样的,只是返回类型不同罢了,根据自己需要调用。

  

  二、利用流读取文件

    分别有StreamReader和FileStream。详细内容请看代码。  

 1             //ReadAllLines
2 Console.WriteLine("--{0}", "ReadAllLines");
3 List<string> list = new List<string>(File.ReadAllLines(filePath));
4 list.ForEach(str =>
5 {
6 Console.WriteLine(str);
7 });
8
9 //ReadAllText
10 Console.WriteLine("--{0}", "ReadAllLines");
11 string fileContent = File.ReadAllText(filePath);
12 Console.WriteLine(fileContent);
13
14 //StreamReader
15 Console.WriteLine("--{0}", "StreamReader");
16 using (StreamReader sr = new StreamReader(filePath))
17 {
18 //方法一:从流的当前位置到末尾读取流
19 fileContent = string.Empty;
20 fileContent = sr.ReadToEnd();
21 Console.WriteLine(fileContent);
22 //方法二:一行行读取直至为NULL
23 fileContent = string.Empty;
24 string strLine = string.Empty;
25 while (strLine != null)
26 {
27 strLine = sr.ReadLine();
28 fileContent += strLine+"\r\n";
29 }
30 Console.WriteLine(fileContent);
31 }

   

7.写入文件

  写文件内容与读取文件类似,请参考读取文件说明。

 1             //WriteAllLines
2 File.WriteAllLines(filePath,new string[]{"11111","22222","3333"});
3 File.Delete(filePath);
4
5 //WriteAllText
6 File.WriteAllText(filePath, "11111\r\n22222\r\n3333\r\n");
7 File.Delete(filePath);
8
9 //StreamWriter
10 using (StreamWriter sw = new StreamWriter(filePath))
11 {
12 sw.Write("11111\r\n22222\r\n3333\r\n");
13 sw.Flush();
14 }

9.文件路径

  文件和文件夹的路径操作都在Path类中。另外还可以用Environment类,里面包含环境和程序的信息。

 1             string dirPath = @"D:\TestDir";
2 string filePath = @"D:\TestDir\TestFile.txt";
3 Console.WriteLine("<<<<<<<<<<<{0}>>>>>>>>>>", "文件路径");
4 //获得当前路径
5 Console.WriteLine(Environment.CurrentDirectory);
6 //文件或文件夹所在目录
7 Console.WriteLine(Path.GetDirectoryName(filePath)); //D:\TestDir
8 Console.WriteLine(Path.GetDirectoryName(dirPath)); //D:\
9 //文件扩展名
10 Console.WriteLine(Path.GetExtension(filePath)); //.txt
11 //文件名
12 Console.WriteLine(Path.GetFileName(filePath)); //TestFile.txt
13 Console.WriteLine(Path.GetFileName(dirPath)); //TestDir
14 Console.WriteLine(Path.GetFileNameWithoutExtension(filePath)); //TestFile
15 //绝对路径
16 Console.WriteLine(Path.GetFullPath(filePath)); //D:\TestDir\TestFile.txt
17 Console.WriteLine(Path.GetFullPath(dirPath)); //D:\TestDir
18 //更改扩展名
19 Console.WriteLine(Path.ChangeExtension(filePath, ".jpg"));//D:\TestDir\TestFile.jpg
20 //根目录
21 Console.WriteLine(Path.GetPathRoot(dirPath)); //D:\
22 //生成路径
23 Console.WriteLine(Path.Combine(new string[] { @"D:\", "BaseDir", "SubDir", "TestFile.txt" })); //D:\BaseDir\SubDir\TestFile.txt
24 //生成随即文件夹名或文件名
25 Console.WriteLine(Path.GetRandomFileName());
26 //创建磁盘上唯一命名的零字节的临时文件并返回该文件的完整路径
27 Console.WriteLine(Path.GetTempFileName());
28 //返回当前系统的临时文件夹的路径
29 Console.WriteLine(Path.GetTempPath());
30 //文件名中无效字符
31 Console.WriteLine(Path.GetInvalidFileNameChars());
32 //路径中无效字符
33 Console.WriteLine(Path.GetInvalidPathChars());

10.文件属性操作  

  File类与FileInfo都能实现。静态方法与实例化方法的区别!

 1             //use File class
2 Console.WriteLine(File.GetAttributes(filePath));
3 File.SetAttributes(filePath,FileAttributes.Hidden | FileAttributes.ReadOnly);
4 Console.WriteLine(File.GetAttributes(filePath));
5
6 //user FilInfo class
7 FileInfo fi = new FileInfo(filePath);
8 Console.WriteLine(fi.Attributes.ToString());
9 fi.Attributes = FileAttributes.Hidden | FileAttributes.ReadOnly; //隐藏与只读
10 Console.WriteLine(fi.Attributes.ToString());
11
12 //只读与系统属性,删除时会提示拒绝访问
13 fi.Attributes = FileAttributes.Archive;
14 Console.WriteLine(fi.Attributes.ToString());

 11.移动文件夹中的所有文件夹与文件到另一个文件夹

  如果是在同一个盘符中移动,则直接调用Directory.Move的方法即可!跨盘符则使用下面递归的方法!

 1         /// <summary>
2 /// 移动文件夹中的所有文件夹与文件到另一个文件夹
3 /// </summary>
4 /// <param name="sourcePath">源文件夹</param>
5 /// <param name="destPath">目标文件夹</param>
6 public static void MoveFolder(string sourcePath,string destPath)
7 {
8 if (Directory.Exists(sourcePath))
9 {
10 if (!Directory.Exists(destPath))
11 {
12 //目标目录不存在则创建
13 try
14 {
15 Directory.CreateDirectory(destPath);
16 }
17 catch (Exception ex)
18 {
19 throw new Exception("创建目标目录失败:" + ex.Message);
20 }
21 }
22 //获得源文件下所有文件
23 List<string> files = new List<string>(Directory.GetFiles(sourcePath));
24 files.ForEach(c =>
25 {
26 string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
27 //覆盖模式
28 if (File.Exists(destFile))
29 {
30 File.Delete(destFile);
31 }
32 File.Move(c, destFile);
33 });
34 //获得源文件下所有目录文件
35 List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
36
37 folders.ForEach(c =>
38 {
39 string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
40 //Directory.Move必须要在同一个根目录下移动才有效,不能在不同卷中移动。
41 //Directory.Move(c, destDir);
42
43 //采用递归的方法实现
44 MoveFolder(c, destDir);
45 });
46 }
47 else
48 {
49 throw new DirectoryNotFoundException("源目录不存在!");
50 }
51 }

12.复制文件夹中的所有文件夹与文件到另一个文件夹

  如果是需要移动指定类型的文件或者包含某些字符的目录,只需在Directory.GetFiles中加上查询条件即可!

 1         /// <summary>
2 /// 复制文件夹中的所有文件夹与文件到另一个文件夹
3 /// </summary>
4 /// <param name="sourcePath">源文件夹</param>
5 /// <param name="destPath">目标文件夹</param>
6 public static void CopyFolder(string sourcePath,string destPath)
7 {
8 if (Directory.Exists(sourcePath))
9 {
10 if (!Directory.Exists(destPath))
11 {
12 //目标目录不存在则创建
13 try
14 {
15 Directory.CreateDirectory(destPath);
16 }
17 catch (Exception ex)
18 {
19 throw new Exception("创建目标目录失败:" + ex.Message);
20 }
21 }
22 //获得源文件下所有文件
23 List<string> files = new List<string>(Directory.GetFiles(sourcePath));
24 files.ForEach(c =>
25 {
26 string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
27 File.Copy(c, destFile,true);//覆盖模式
28 });
29 //获得源文件下所有目录文件
30 List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
31 folders.ForEach(c =>
32 {
33 string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
34 //采用递归的方法实现
35 CopyFolder(c, destDir);
36 });
37 }
38 else
39 {
40 throw new DirectoryNotFoundException("源目录不存在!");
41 }
42 }

(转)C#文件操作的更多相关文章

  1. 【.NET深呼吸】Zip文件操作(1):创建和读取zip文档

    .net的IO操作支持对zip文件的创建.读写和更新.使用起来也比较简单,.net的一向作风,东西都准备好了,至于如何使用,请看着办. 要对zip文件进行操作,主要用到以下三个类: 1.ZipFile ...

  2. 野路子出身PowerShell 文件操作实用功能

    本文出处:http://www.cnblogs.com/wy123/p/6129498.html 因工作需要,处理一批文件,本想写C#来处理的,后来想想这个是PowerShell的天职,索性就网上各种 ...

  3. Node基础篇(文件操作)

    文件操作 相关模块 Node内核提供了很多与文件操作相关的模块,每个模块都提供了一些最基本的操作API,在NPM中也有社区提供的功能包 fs: 基础的文件操作 API path: 提供和路径相关的操作 ...

  4. 归档NSKeyedArchiver解归档NSKeyedUnarchiver与文件管理类NSFileManager (文件操作)

    ========================== 文件操作 ========================== 一.归档NSKeyedArchiver 1.第一种方式:存储一种数据. // 归档 ...

  5. SQL Server附加数据库报错:无法打开物理文件,操作系统错误5

    问题描述:      附加数据时,提示无法打开物理文件,操作系统错误5.如下图: 问题原因:可能是文件访问权限方面的问题. 解决方案:找到数据库的mdf和ldf文件,赋予权限即可.如下图: 找到mdf ...

  6. 通过cmd完成FTP上传文件操作

    一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...

  7. Linux文件操作的主要接口API及相关细节

    操作系统API: 1.API是一些函数,这些函数是由linux系统提供支持的,由应用层程序来使用,应用层程序通过调用API来调用操作系统中的各种功能,来干活 文件操作的一般步骤: 1.在linux系统 ...

  8. C语言的fopen函数(文件操作/读写)

    头文件:#include <stdio.h> fopen()是一个常用的函数,用来以指定的方式打开文件,其原型为:    FILE * fopen(const char * path, c ...

  9. Python的文件操作

    文件操作,顾名思义,就是对磁盘上已经存在的文件进行各种操作,文本文件就是读和写. 1. 文件的操作流程 (1)打开文件,得到文件句柄并赋值给一个变量 (2)通过句柄对文件进行操作 (3)关闭文件 现有 ...

  10. python 文件操作(转)

    python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目 ...

随机推荐

  1. linux中ls、ls -l、ls -al、ll命令

    ls只是简单的列出目录下文件名,ll更加详细的列出了文件的类型.文件所有者权限.文件所有者组权限.文件大小.文件最后修改时间,etc... 我们可以用一个简单的图来说明,如下图1: 图1 1.第一位就 ...

  2. ubuntu各版本的区别

    ubuntu.kubuntu以及xubuntu的区别Ubuntu默认是Gnome:KUbuntu用的是KDE,效果比较炫目,但是系统要求也较高XUbuntu用的是Xface,比较轻量,系统要求较低,推 ...

  3. Infinite Scroll–无限分页

    一.前言 现在有很多网站都有这样的交互 1.当你往下浏览页面时,页面会自动去异步加载数据. 无限分页效果 infinite scroll 效果图 –ifxoxo.com 2.在页面下方有一个“点击加载 ...

  4. 【Java】对Web Service的理解

    WSDL(Web Service Description Language)是描述Web Service的语言. 你会怎样向别人介绍你的Web service有什么功能,以及每个函数调用时的参数呢?你 ...

  5. 【转】如何开发苹果iOS操作平台下的应用程序?

    原文网址:http://zhidao.baidu.com/link?url=vxRWjCchSstFmVKvxEqLqfqomu2h5kF-NLAIVEehQgN_FnYtEi4f5yPMS6ywbU ...

  6. 动态规划:NOI2013 快餐店

    Description 小 T打算在城市C开设一家外送快餐店.送餐到某一个地点的时间与外卖店到该地点之间最短路径长度是成正比的,小T希望快餐店的地址选在离最远的顾客距离最近 的地方. 快餐店的顾客分布 ...

  7. 数据结构(左偏树):HDU 1512 Monkey King

    Monkey King Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tota ...

  8. HDOJ 2027 统计元音

    Problem Description 统计每个元音字母在字符串中出现的次数. Input 输入数据首先包括一个整数n,表示测试实例的个数,然后是n行长度不超过100的字符串. Output 对于每个 ...

  9. Codeforces Round #324 (Div. 2)解题报告

    ---恢复内容开始--- Codeforces Round #324 (Div. 2) Problem A 题目大意:给二个数n.t,求一个n位数能够被t整除,存在多组解时输出任意一组,不存在时输出“ ...

  10. windows Compiler toolchain env

    1,gygwin