操作文件方法简单总结(File,Directory,StreamReader,StreamWrite )(转载)
本文转自http://www.cnblogs.com/zery/p/3315889.html
对于文件夹,文档的操作一直处于一知半解状态,有时间闲下来了,好好练习了一把,对文档,文件的操作有了一个基本的认知,
若要深入了解,还是得通过实际的项目才行了,好了废话不多说,上酸菜!!
注:红色标题为园友@李大菜鸟与@flyher补充的方法再次感谢
一 基本介绍
操作文档,文件夹,需要用到的类
1 Directory(静态类) : 用于创建、移动和删除等操作通过目录和子目录
DirectoryInfo(非静态):
2 File(静态类) :提供用于创建、复制、删除、移动和打开文件的静态类,并协助创建 FileStream 对象
FileInfo(非静态)
3 StreamReader:实现一个 TextReader,使其以一种特定的编码从字节流中读取字符
StreamWriter:实现一个 TextWriter,使其以一种特定的编码向流中写入字符
二 文件夹操作
操作文件夹用Directory 或者 DirectoryInfo
2.1 创建文件夹
string path = @"F:\TestFile";
//创建文件夹
public void CreatFolder(string path)
{
if (Directory.Exists(path))
{
Directory.Delete(path);
}
Directory.CreateDirectory(path); }
展开代码
2.2 删除文件夹
string path = @"F:\TestFile";
//删除文件夹
public void DeleteFolder(string path)
{
//先删除文件夹中所有文件
DirectoryInfo directoryInfo = new DirectoryInfo(path);
foreach (var directory in directoryInfo.GetFiles())
{
File.Delete(directory.FullName);
}
//文件夹必须为空
if (Directory.Exists(path))
{
Directory.Delete(path);
}
}
展开代码
2.3 移动文件夹
string path = @"F:\TestFile";
string newPath = @"F:\NewFile";
//移动文件夹
public void MoveFolder(string path, string newPath)
{
if (Directory.Exists(path))
{
//移动包括文件夹在内的所有文件
Directory.Move(path,newPath);
}
}
展开代码
2.4 获取文件夹下所有文件名
string path = @"F:\TestFile";
//获取文件夹下所有文件名
public void GetFolderAllFiles(string path)
{
DirectoryInfo directory = new DirectoryInfo(path);
var files = directory.GetFiles();
foreach (var file in files)
{
Console.WriteLine(file.Name);
Console.WriteLine(file.FullName);//带文件路径全名
}
}
展开代码
2.5 文件夹重命名
其实与移动文件夹方法是一样的,.net并没有提供重命名的方法,而是用新路径替换原路径以达到重命名的交果
string name = @"F:\TestFile";
string newName = @"F:\NewFile";
//文件夹重命名
public void Rename(string name ,string newName)
{
if (Directory.Exists(name))
{
File.Move(name,newName);
}
}
展开代码
2.6 获取文件夹下所有文件夹名
string path = @"F:\TestFile";
//获取路径下所有文件夹
public void GetAllFolder(string path)
{
DirectoryInfo directory = new DirectoryInfo(path);
DirectoryInfo[] allFolder = directory.GetDirectories();//返回当前目录的子目录(文件夹)
foreach (var folder in allFolder)
{
Console.WriteLine(folder.Name);
Console.WriteLine(folder.FullName);//带全路径的名称
//还可以再遍历子文件夹里的文件,或文件夹(最好用递归的方式)
folder.GetDirectories();
}
}
展开代码
2.7 处理路径得到文件名和文件后缀
string path = @"F:\TestFile";
//处理路径得到文件名和文件后缀,
public void FormatFile(string path)
{
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles();
foreach (var file in files)
{
string name = Path.GetFileNameWithoutExtension(file.Name);//取文件名
string extension = Path.GetExtension(file.Name);//取后缀名
Console.WriteLine("文件名:{0} 后缀名:{1}",name,extension);
}
}
展开代码
2.8 判断路径是文件或者文件夹(无效路径返回0)
string path = @"F:\TestFile";
//判断路径是文件或者文件夹(无效路径返回0)
public void IsFileOrFolder(string path)
{
DirectoryInfo directory = new DirectoryInfo(path);
if (directory.Exists)//指定的目录是否存在
Console.WriteLine("Folder");
else if (File.Exists(path))//指定的文件是否存在
Console.WriteLine("File");
else
Console.WriteLine("");
}
展开代码
三 文档操作(txt)
需要以下几个类:Directory 或者DirectoryInfo ,File 或者 FileInfo
3.1 创建文档
string path = @"F:\TestFile\test.txt";
//创建文档
public void CreateFile(string path)
{
//文件路径用Directory判断是否存在
if (Directory.Exists(path))
{
//先删除存在的文件
if (File.Exists(path))
{
File.Delete(path);
}
File.Create(path);
}
}
展开代码
3.2 复制文档
string path = @"E:\TestFile\test.txt";
string newPath = @"E:\Test2File\newTest.txt";
//复制文档
public void CopyFile(string sourcePath, string destPath)
{
//只能针对同一卷轴(盘)下的文件
//destPath 为要复制的新地址,(destPath指定的文件名必须是未创建的,执行Copy方法时才会创建该文件)
if (File.Exists(sourcePath))
{
File.Copy(sourcePath, destPath);
}
}
3.3 移动文档
string path = @"E:\TestFile\test.txt";
string newPath = @"E:\Test2File\newTest.txt";
//移动文档
public void MoveFile(string SourcePath, string destPath)
{
//只能针对同一卷轴(盘)下的文件
//destPath 为要移动的新地址(destPath指定的文件名必须是未创建的,执行Move方法时会将Source文件移动到新地址可以重新命名)
if (File.Exists(SourcePath))
{
File.Move(SourcePath, destPath);
}
}
展开代码
3.4 删除文档
string path = @"E:\TestFile\test.txt";
//删除文档
public void DeleteFile(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
展开代码
四 文档读写操作(文档流操作) 对 第三点 的扩充
需要以下类:FileStream 此类继承了Stream 类并重写了大部分方法,并提供多个带参构造函数,注意:要读取的目标流不是保持恒定的,而是每读一次就会相应的减少,在练习时
没注意,纠结了很久
4.1 写入字符
string path = @"E:\TestFile\test.txt";
//往以有文档中写入字符
public void CreateText(string path)
{
StreamWriter writer=File.CreateText(path);
//直接写入字符的write方法,每次写入都会覆盖之前的内容
writer.Write("你好!");
//把缓存流的数据写入到基础流
writer.Flush();
//关闭StreamWriter对象及基础流
writer.Close();
}
展开代码
4.2 以流的形式写入文档
//将一个文件内的数据,以流的方式读取,然后以流的形式写入到另一个文件中
public void ReadAndWriteFile()
{
string readPath = @"E:\TestFile\ReadStream.txt";
string writePath = @"E:\TestFile\WriteStream.txt"; //Read
//打开现有文件以进行读取
FileStream rs = File.OpenRead(readPath);
byte[] buffer = new byte[rs.Length];
rs.Read(buffer, , buffer.Length); //将文件内容读到字节流中
rs.Close();
//Write
//打开现有文件以进行写入
FileStream stream = File.OpenWrite(writePath);
stream.Write(buffer, , buffer.Length);
stream.Flush();
stream.Close(); }
展开代码
4.3 以流的形式追加到文档
//将一个文件内的数据,以流的方式读取,然后以流的形式写入到另一个文件中(追加内容)
public void ReadAndWriteNewFile()
{
string readPath = @"E:\TestFile\ReadStream.txt";
string writePath = @"E:\TestFile\WriteStream.txt";
//Read
FileStream rd = File.Open(readPath,FileMode.Open);
byte[] buffer = new byte[rd.Length];
rd.Read(buffer, , buffer.Length);
rd.Close(); //Write
FileStream wt = File.Open(writePath,FileMode.Append);//设为追加到原文件中
wt.Write(buffer,,buffer.Length);
wt.Flush();
wt.Close();
}
展开代码
4.4 读取目标文档指定的一行数据
string paths = @"F:\TestFile\ReadStream.txt";
int readNum = ;
//读取目标文本指定的某一行数据
public void ReadoneLine(string path,int readNum)
{
//可以循环读每一行,然后到Add到集合中,再到集合中做处理
StreamReader reader = new StreamReader(path,Encoding.Default);
var streamList = new List<string>();
int count=;
string lineText = string.Empty; while ((lineText = reader.ReadLine()) != null)//对于流的读取每ReadLine一次流中就少一行,所直接在While用读到的流做判断,避免二次读
{
streamList.Add(lineText);
} foreach (var item in streamList)
{
if (count == readNum - )
{
Console.WriteLine(item);
}
count++;
} }
展开代码
4.5 循环读取文件
static void Main(string[] args)
{
string readPath = @"c:\TestFile\a.rar";
string writePath = @"c:\TestFile\b.rar"; //Read
//打开现有文件以进行读取
FileStream rs = File.OpenRead(readPath);
FileStream stream = File.OpenWrite(writePath);
byte[] buffer = new byte[];
int nRead = ;
decimal dTotal = ;
while ((nRead = rs.Read(buffer, , buffer.Length))>)
{
dTotal += (decimal)nRead / (decimal)rs.Length; Console.WriteLine(dTotal);
stream.Write(buffer, , buffer.Length);
} rs.Close();
//Write
//打开现有文件以进行写入 stream.Flush();
stream.Close();
}
五 读写流操作文档
需要以下几个类:StreamReader StreamWriter
5.1 字符串读取写操作
//读取文档并写入到另一文档中(用字符串写入的方法)
public void ReadFile()
{
string readPath = @"E:\TestFile\ReadStream.txt";
string writePath = @"E:\TestFile\WriteStream.txt"; using (StreamReader reader = new StreamReader(readPath,Encoding.Default)) //用默认的编码格式(必须要转格式否则乱码)
{ var rd = reader.ReadToEnd(); StreamWriter writer = new StreamWriter(writePath,true,Encoding.UTF8);//需要转成UTF-8的格式(可转可不转格式)
writer.Write(rd);
writer.Flush();
writer.Close(); }
}
展开代码
5.2 字符流读写操作
//用字符流的方式读写文档
public void ReadWriteByByte()
{ string readPath = @"F:\TestFile\ReadStream.txt";
string writePath = @"F:\TestFile\WriteStream.txt";
using (StreamReader reader = new StreamReader(readPath,Encoding.Default))//需要指定编码,否则读到的为乱码
{
#region 错误方法
//Read 注意:文本中的字符只能被读取一次,第二次时读取不到了
//var readStr =reader.ReadToEnd();//第一次读取
//char[] buffer = new char[readStr.Length];
//reader.Read(buffer, 0, buffer.Length);//第二次读取时,读不到值
#endregion
//Read
char[] buffer = new char[];
reader.Read(buffer, , buffer.Length);
//Write
StreamWriter writer = new StreamWriter(writePath,true,Encoding.UTF8);
writer.Write(buffer, , buffer.Length);
writer.Flush();
writer.Close();
}
展开代码
六 总结
本文只对以上几个类常用的方法简单的介绍了,也是扫了下自己的盲区,如有更好的建议或方法,请指出。
另外如果觉得本文对你有一点小小的帮助不妨点下推荐,您的推荐是我写作的动力!!
操作文件方法简单总结(File,Directory,StreamReader,StreamWrite )(转载)的更多相关文章
- 操作文件方法简单总结(File,Directory,StreamReader,StreamWrite )
对于文件夹,文档的操作一直处于一知半解状态,有时间闲下来了,好好练习了一把,对文档,文件的操作有了一个基本的认知, 若要深入了解,还是得通过实际的项目才行了,好了废话不多说,上酸菜!! 注:红色标题为 ...
- 操作文件方法简单总结(File,Directory,StreamReader,StreamWrite ) - Zery-zhang
一 基本介绍 操作文档,文件夹,需要用到的类 1 Directory (静态类) : 用于创建.移动和删除等操作通过 目录 和子 目录 DirectoryInfo (非静态): 2 File ...
- 【Python】 文件和操作文件方法
文件 ■ 基本的文件用法 f = open("path","mode") mode有a,w,r,b,+等.默认为r.模式与打开文件时的动作有关系,比如用w打开的 ...
- linq操作文件方法
备忘 string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); List<File ...
- 【Android Studio 小技巧】一键查看文件方法结构目录File Structure
看源代码的时候,如果可以查看class中的所有方法,可以提高效率.Android Studio 中可以使用快捷键一键显示所有方法的目录. Mac: command + fn + F12 (在mac中的 ...
- 使用File类、StreamRead和StreamWrite读写数据、以及Path类操作文件路径和Directory
1.File类的概念: File类,是一个静态类,主要是来提供一些函数库用的.静态实用类,提供了很多静态的方法,支持对文件的基本操作,包括创建,拷贝,移动,删除和 打开一个文件. File类方法的参量 ...
- java File文件操作共用方法整理
package org.jelly.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io ...
- .net(C#)操作文件的几种方法汇总
.net(C#)操作文件的几种方法汇总 System.IO命名空间下类的用法:在System.IO名称空间中包含了用于文件输入输出的主要类.File:实用类,提供许多静态方法,用于移动.复制和删除文件 ...
- C#操作文件夹及文件的方法的使用
本文收集了目前最为常用的C#经典操作文件的方法,具体内容如下:C#追加.拷贝.删除.移动文件.创建目录.递归删除文件夹及文件.指定文件夹下面的所有内容copy到目标文件夹下面.指定文件夹下面的所有内容 ...
随机推荐
- linux日常管理-free查看内存工具
查看内存 命令 free 默认是k为单位 也可以指定 m为单位 或者G为单位,这个不精准 total 总容量 used 使用了多少 free 剩余多少 看第二行.第一行是物理内存,加上虚拟内存b ...
- Math类简介
Math abs max min 分别是绝对值 最大值,最小值 round 四舍五入 ceil ceil(32.6) 33.0 ceil(32.2) 33.0 返回大于该数值的较大的整数 与之相对 ...
- [codeforces821E]Okabe and El Psy Kongroo
题意:(0,0)走到(k,0),每一部分有一条线段作为上界,求方案数. 解题关键:dp+矩阵快速幂,盗个图,注意ll 关于那条语句为什么不加也可以,因为我的矩阵C,就是因为多传了了len的原因,其他位 ...
- java poi导出Excel 总结
首先下载 Apache 的POI jar包 将更目录下的poi-3.8-20120326.jar 和lib下的三个jar包导入 如下图: 首先必须搞一个通用的工具类,网上找的,能用就行,java就是这 ...
- ubuntu下root用户默认密码及修改方法
[ubuntu下root用户默认密码及修改方法] 很多朋友用ubuntu,一般都是装完ubuntu系统,马上就修改root密码了,那么root用户的默认密码是多少,当忘记root用户密码时如何找回呢, ...
- p3627&bzoj1179 抢掠计划(ATM)
传送门(洛谷) 传送门(bzoj) 题目 Siruseri 城中的道路都是单向的.不同的道路由路口连接.按照法律的规定, 在每个路口都设立了一个 Siruser i 银行的 ATM 取款机.令人奇怪的 ...
- Linux awk指令详解
简介 awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再 ...
- 10.Redis未授权访问漏洞复现与利用
一.漏洞简介以及危害: 1.什么是redis未授权访问漏洞: Redis 默认情况下,会绑定在 0.0.0.0:6379,如果没有进行采用相关的策略,比如添加防火墙规则避免其他非信任来源 ip 访问等 ...
- HN669打包工具--调试文档
调试有两种方式,一是直接在游戏工程上面调试,这比较麻烦,需要根据插件配置文件和脚本文件去配置好工程选项后,才能调试.简单一点就是通过脚本文件打包后会有生成游戏工程对应每个渠道的工程. 如下图:这个工程 ...
- C#对Execl操作类
1.NuGet下安装 NPOI 2.实例代码:(可以根据具体情况注释和添加代码逻辑) public class ExeclHelper { /// <summary> /// 将excel ...