C#之文本操作
【转载】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#之文本操作的更多相关文章
- Linux命令-文件文本操作grep
文件文本操作 grep 在文件中查找符合正则表达式条件的文本行 cut 截取文件中的特定字段 paste 附加字段 tr 字符转换或压缩 sort 调整文本行的顺序,使其符合特定准则 uniq 找出重 ...
- linux文本操作界面 vi面板如何复制一行
linux文本操作界面 vi面板如何复制一行 1)把光标移动到要复制的行上2)按yy3)把光标移动到要复制的位置4)按p 在vi里如何复制一行中间的几个字符?如果你要从光标处开始复制 4 个字符,则先 ...
- HTML&CSS基础学习笔记1.6-html的文本操作标签
文本也许是HTML里最常见的元素了,所以我们有必要对HTML的文本操作标签做下认识. 1. <em>,<i>内的文字呈现为倾斜效果: 2. <strong>,< ...
- 如何设置secureCRT的鼠标右键为弹出文本操作菜单功能
secureCRT的鼠标右键功能默认是粘贴的功能,用起来和windows系统的风格不一致, 如果要改为右键为弹出文本操作菜单功能,方便对选择的内容做拷贝编辑操作,可以在 options菜单----&g ...
- jQuery 选择器 筛选器 样式操作 文本操作 属性操作 文档处理 事件 动画效果 插件 each、data、Ajax
jQuery jQuery介绍 1.jQuery是一个轻量级的.兼容多浏览器的JavaScript库. 2.jQuery使用户能够更方便地处理HTML Document.Events.实现动画效果.方 ...
- Shell命令之文本操作
前言 在Linux中,文本处理操作是最常见的,应用非常广泛,如果能熟练掌握,可以大大提高开发效率. awk/sed/grep是文本操作领域的“三剑客”,学会了这3个命令就可以应对绝大多数文本处理场景. ...
- python中的文本操作
python如何进行文本操作 1.能调用方法的一定是对象,比如数值.字符串.列表.元组.字典,甚至文件也是对象,Python中一切皆为对象. str1 = 'hello' str2 = 'world' ...
- jQuery-对标签元素 文本操作-属性操作-文档的操作
一.对标签元素文本操作 1.1 对标签中内容的操作 // js var div1 = document.getElementById("div1"); div1.innerText ...
- 文本操作 $(..).text() $(..).html() $(..).val()最后一种主要用于input
文本操作: $(..).text() # 获取文本内容 $(..).text('<a>1</a>') # 设置文本内容 $(..).html() $(..).html('< ...
- linux下的文本操作之 文本查找——grep
摘要:你有没有这样的应用场景:调试一个程序,出现debug的提示信息,现在你需要定位是哪个文件包含了这个debug信息,也就是说,你需要在一个目录下的多个文件(可能包含子目录)中查找某个字符串的位置: ...
随机推荐
- validate jquery 注册页面使用实例 详解
官方使用文档:http://jqueryvalidation.org/documentation/ 参考资料:http://www.w3cschool.cc/jquery/jquery-plugin- ...
- Reachability(判断网络是否连接)
类似于一个网络状况的探针. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabili ...
- android自定义控件(1)-点击实现开关按钮切换
自定义控件的步骤.用到的主要方法: 1.首先需要定义一个类,继承自View:对于继承View的类,会需要实现至少一个构造方法:实际上这里一共有三个构造方法: public View (Contex ...
- 代码中access 的使用
C++代码:if(access(strZip.c_str(), 0) == 0){...} 此处为判断strZip中文件是否存在 .c_str() 是他自身字符串名称,该名称是一个压缩文件 ...
- svn更改分支名字,move命令
名称 svn move — 移动一个文件或目录. 概要 svn move SRC DST 描述 这个命令移动文件或目录到你的工作拷贝或者是版本库. 提示 这个命令同svn copy加一个svn del ...
- PostgreSQL表空间、数据库、模式、表、用户/角色之间的关系
看PostgreSQL9的官方文档,我越看越迷糊,这表空间,数据库,模式,表,用户,角色之间的关系怎么在PostgreSQL里这么混乱呢?经过中午的一个小实验,我逐渐理清了个中来龙去脉.下面我来还原我 ...
- WebSocket帧数据 解码/转码
数据从浏览器通过websocket发送给服务器的数据,是原始的帧数据,默认是被掩码处理过的,所以需要对其利用掩码进行解码. 从服务器发送给浏览器的数据是默认没有掩码处理的,只要符合一定结构就可以了.具 ...
- HDU 1058 Humble Numbers(离线打表)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1058 解题报告:输入一个n,输出第n个质因子只有2,3,5,7的数. 用了离线打表,因为n最大只有58 ...
- BZOJ3052——糖果公园
0.题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=3052 1.题目大意:给定一颗n个点的无根树,每个点有一个颜色,要进行q次操作,有两种操 ...
- CSS3中动画属性transform、transition和animation
Transform:变形 在网页设计中,CSS被习惯性的理解为擅长表现静态样式,动态的元素必须借助于javascript才可以实现,而CSS3的出现改变了这一思维方式.CSS3除了增加革命性的创新功能 ...