【转载】C#文件操作大全(SamWang)

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

  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.找出下层文件和文件夹路径迭代删除

      /// <summary>
/// 删除指定目录下所有内容:方法一--删除目录,再创建空目录
/// </summary>
/// <param name="dirPath"></param>
public static void DeleteDirectoryContentEx(string dirPath)
{
if (Directory.Exists(dirPath))
{
Directory.Delete(dirPath);
Directory.CreateDirectory(dirPath);
}
} /// <summary>
/// 删除指定目录下所有内容:方法二--找到所有文件和子文件夹删除
/// </summary>
/// <param name="dirPath"></param>
public static void DeleteDirectoryContent(string dirPath)
{
if (Directory.Exists(dirPath))
{
foreach (string content in Directory.GetFileSystemEntries(dirPath))
{
if (Directory.Exists(content))
{
Directory.Delete(content, true);
}
else if (File.Exists(content))
{
File.Delete(content);
}
}
}
}

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。详细内容请看代码。  

         //ReadAllLines
Console.WriteLine("--{0}", "ReadAllLines");
List<string> list = new List<string>(File.ReadAllLines(filePath));
list.ForEach(str =>
{
Console.WriteLine(str);
}); //ReadAllText
Console.WriteLine("--{0}", "ReadAllLines");
string fileContent = File.ReadAllText(filePath);
Console.WriteLine(fileContent); //StreamReader
Console.WriteLine("--{0}", "StreamReader");
using (StreamReader sr = new StreamReader(filePath))
{
//方法一:从流的当前位置到末尾读取流
fileContent = string.Empty;
fileContent = sr.ReadToEnd();
Console.WriteLine(fileContent);
//方法二:一行行读取直至为NULL
fileContent = string.Empty;
string strLine = string.Empty;
while (strLine != null)
{
strLine = sr.ReadLine();
fileContent += strLine+"\r\n";
}
Console.WriteLine(fileContent);
}

  

7.写入文件

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

     //WriteAllLines
File.WriteAllLines(filePath,new string[]{"","",""});
File.Delete(filePath); //WriteAllText
File.WriteAllText(filePath, "11111\r\n22222\r\n3333\r\n");
File.Delete(filePath); //StreamWriter
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write("11111\r\n22222\r\n3333\r\n");
sw.Flush();
}

9.文件路径

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

     string dirPath = @"D:\TestDir";
string filePath = @"D:\TestDir\TestFile.txt";
Console.WriteLine("<<<<<<<<<<<{0}>>>>>>>>>>", "文件路径");
//获得当前路径
Console.WriteLine(Environment.CurrentDirectory);
//文件或文件夹所在目录
Console.WriteLine(Path.GetDirectoryName(filePath)); //D:\TestDir
8 Console.WriteLine(Path.GetDirectoryName(dirPath)); //D:\
//文件扩展名
Console.WriteLine(Path.GetExtension(filePath)); //.txt
//文件名
Console.WriteLine(Path.GetFileName(filePath)); //TestFile.txt
Console.WriteLine(Path.GetFileName(dirPath)); //TestDir
Console.WriteLine(Path.GetFileNameWithoutExtension(filePath)); //TestFile
//绝对路径
Console.WriteLine(Path.GetFullPath(filePath)); //D:\TestDir\TestFile.txt
Console.WriteLine(Path.GetFullPath(dirPath)); //D:\TestDir
//更改扩展名
Console.WriteLine(Path.ChangeExtension(filePath, ".jpg"));//D:\TestDir\TestFile.jpg
//根目录
Console.WriteLine(Path.GetPathRoot(dirPath)); //D:\
//生成路径
Console.WriteLine(Path.Combine(new string[] { @"D:\", "BaseDir", "SubDir", "TestFile.txt" })); //D:\BaseDir\SubDir\TestFile.txt
//生成随即文件夹名或文件名
Console.WriteLine(Path.GetRandomFileName());
//创建磁盘上唯一命名的零字节的临时文件并返回该文件的完整路径
Console.WriteLine(Path.GetTempFileName());
//返回当前系统的临时文件夹的路径
Console.WriteLine(Path.GetTempPath());
//文件名中无效字符
Console.WriteLine(Path.GetInvalidFileNameChars());
//路径中无效字符
Console.WriteLine(Path.GetInvalidPathChars());

10.文件属性操作  

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

      //use File class
Console.WriteLine(File.GetAttributes(filePath));
File.SetAttributes(filePath,FileAttributes.Hidden | FileAttributes.ReadOnly);
Console.WriteLine(File.GetAttributes(filePath)); //user FilInfo class
FileInfo fi = new FileInfo(filePath);
Console.WriteLine(fi.Attributes.ToString());
fi.Attributes = FileAttributes.Hidden | FileAttributes.ReadOnly; //隐藏与只读
Console.WriteLine(fi.Attributes.ToString()); //只读与系统属性,删除时会提示拒绝访问
fi.Attributes = FileAttributes.Archive;
Console.WriteLine(fi.Attributes.ToString());

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

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

    /// <summary>
/// 移动文件夹中的所有文件夹与文件到另一个文件夹
/// </summary>
/// <param name="sourcePath">源文件夹</param>
/// <param name="destPath">目标文件夹</param>
public static void MoveFolder(string sourcePath,string destPath)
{
if (Directory.Exists(sourcePath))
{
if (!Directory.Exists(destPath))
{
//目标目录不存在则创建
try
{
Directory.CreateDirectory(destPath);
}
catch (Exception ex)
{
throw new Exception("创建目标目录失败:" + ex.Message);
}
}
//获得源文件下所有文件
List<string> files = new List<string>(Directory.GetFiles(sourcePath));
files.ForEach(c =>
{
string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
//覆盖模式
if (File.Exists(destFile))
{
File.Delete(destFile);
}
32 File.Move(c, destFile);
});
//获得源文件下所有目录文件
List<string> folders = new List<string>(Directory.GetDirectories(sourcePath)); folders.ForEach(c =>
{
string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
//Directory.Move必须要在同一个根目录下移动才有效,不能在不同卷中移动。
//Directory.Move(c, destDir); //采用递归的方法实现
MoveFolder(c, destDir);
});
}
else
{
throw new DirectoryNotFoundException("源目录不存在!");
}
}

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

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

    /// <summary>
/// 复制文件夹中的所有文件夹与文件到另一个文件夹
/// </summary>
/// <param name="sourcePath">源文件夹</param>
/// <param name="destPath">目标文件夹</param>
public static void CopyFolder(string sourcePath,string destPath)
{
if (Directory.Exists(sourcePath))
{
if (!Directory.Exists(destPath))
{
//目标目录不存在则创建
try
14 {
Directory.CreateDirectory(destPath);
}
catch (Exception ex)
{
throw new Exception("创建目标目录失败:" + ex.Message);
}
}
//获得源文件下所有文件
List<string> files = new List<string>(Directory.GetFiles(sourcePath));
files.ForEach(c =>
{
string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
File.Copy(c, destFile,true);//覆盖模式
});
//获得源文件下所有目录文件
List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
folders.ForEach(c =>
{
string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
//采用递归的方法实现
CopyFolder(c, destDir);
});
}
38 else
{
throw new DirectoryNotFoundException("源目录不存在!");
}
}

总结:

  有关文件的操作的内容非常多,不过几乎都是从上面的这些基础方法中演化出来的。比如对内容的修改,不外乎就是加上点字符串操作或者流操作。还有其它一些特别的内容,等在开发项目中具体遇到后再添加。

C#之文本操作的更多相关文章

  1. Linux命令-文件文本操作grep

    文件文本操作 grep 在文件中查找符合正则表达式条件的文本行 cut 截取文件中的特定字段 paste 附加字段 tr 字符转换或压缩 sort 调整文本行的顺序,使其符合特定准则 uniq 找出重 ...

  2. linux文本操作界面 vi面板如何复制一行

    linux文本操作界面 vi面板如何复制一行 1)把光标移动到要复制的行上2)按yy3)把光标移动到要复制的位置4)按p 在vi里如何复制一行中间的几个字符?如果你要从光标处开始复制 4 个字符,则先 ...

  3. HTML&CSS基础学习笔记1.6-html的文本操作标签

    文本也许是HTML里最常见的元素了,所以我们有必要对HTML的文本操作标签做下认识. 1. <em>,<i>内的文字呈现为倾斜效果: 2. <strong>,< ...

  4. 如何设置secureCRT的鼠标右键为弹出文本操作菜单功能

    secureCRT的鼠标右键功能默认是粘贴的功能,用起来和windows系统的风格不一致, 如果要改为右键为弹出文本操作菜单功能,方便对选择的内容做拷贝编辑操作,可以在 options菜单----&g ...

  5. jQuery 选择器 筛选器 样式操作 文本操作 属性操作 文档处理 事件 动画效果 插件 each、data、Ajax

    jQuery jQuery介绍 1.jQuery是一个轻量级的.兼容多浏览器的JavaScript库. 2.jQuery使用户能够更方便地处理HTML Document.Events.实现动画效果.方 ...

  6. Shell命令之文本操作

    前言 在Linux中,文本处理操作是最常见的,应用非常广泛,如果能熟练掌握,可以大大提高开发效率. awk/sed/grep是文本操作领域的“三剑客”,学会了这3个命令就可以应对绝大多数文本处理场景. ...

  7. python中的文本操作

    python如何进行文本操作 1.能调用方法的一定是对象,比如数值.字符串.列表.元组.字典,甚至文件也是对象,Python中一切皆为对象. str1 = 'hello' str2 = 'world' ...

  8. jQuery-对标签元素 文本操作-属性操作-文档的操作

    一.对标签元素文本操作 1.1 对标签中内容的操作 // js var div1 = document.getElementById("div1"); div1.innerText ...

  9. 文本操作 $(..).text() $(..).html() $(..).val()最后一种主要用于input

    文本操作: $(..).text() # 获取文本内容 $(..).text('<a>1</a>') # 设置文本内容 $(..).html() $(..).html('< ...

  10. linux下的文本操作之 文本查找——grep

    摘要:你有没有这样的应用场景:调试一个程序,出现debug的提示信息,现在你需要定位是哪个文件包含了这个debug信息,也就是说,你需要在一个目录下的多个文件(可能包含子目录)中查找某个字符串的位置: ...

随机推荐

  1. Lucene.Net+盘古分词->开发自己的搜索引擎

    //封装类 using System;using System.Collections.Generic;using System.Linq;using System.Web;using Lucene. ...

  2. OC-类方法

    类方法 1. 基本概念 直接可以用类名来执行的方法(类本身会在内存中占据存储空间,里面有类\对象方法列表) 2. 类方法和对象方法对比 1)  对象方法 以减号-开头 只能让对象调用,没有对象,这个方 ...

  3. django,python,svn_web

  4. Java操作Oracle

    public class DBCon { // 数据库驱动对象 public static final String DRIVER = "oracle.jdbc.driver.OracleD ...

  5. Serializer序列化/反序列化DateTime少了8小时问题解决

    1.举例子 JavascriptSerializer serializer = new JavascriptSerializer(); DateTime now = DateTime.Parse(&q ...

  6. 由Collections.unmodifiableList引发的重构

    原文  http://www.cnblogs.com/persist-confident/p/4516741.html 今天阅读源码的时候,无意中看到了Collections.unmodifiable ...

  7. C# web api返回类型设置为json的两种方法

    web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 方法一:(改配置法) 找到Global.asax文件,在Applic ...

  8. vim的寄存器和剪贴簿操作?

    vim 复制/ 删除 多行? 有确定序号的行: :10,15m20, 10,15co20 没有确定序号的行: ndd, nyy. 其中的n表示, 从当前行开始算起(当前行本身要包含!!!), 向下共删 ...

  9. fatal: Paths with -a does not make sense.

    git commit -am '*屏蔽设置缓存' htdocs/s.php fatal: Paths with -a does not make sense. 应该用下面的这样. git commit ...

  10. acdream1421 TV Show (枚举)

    http://acdream.info/problem?pid=1421 Andrew Stankevich Contest 22 TV Show Special JudgeTime Limit: 2 ...