c# IO操作
今天我们主要讨论的IO的一些操作,首先我们先引入三个变量:
/// <summary>
/// 配置绝对路径
/// </summary>
private static string LogPath = ConfigurationManager.AppSettings["LogPath"];
private static string LogMovePath = ConfigurationManager.AppSettings["LogMovePath"];
/// <summary>
/// 获取当前程序路径,找到当前运行的exe程序所在的全路径即是D:\\...\\bin\\Debug\\
/// </summary>
private static string LogPath2 = AppDomain.CurrentDomain.BaseDirectory;
以下代码会用到上面的变量!
一:Directory操作类
if (!Directory.Exists(LogPath)) //判断文件夹是否存在
{
//一次性创建全部的子路径,如果文件夹存在不报错 D:\\testIo\\20190131\\Log\\
DirectoryInfo directoryInfo = Directory.CreateDirectory(LogPath); //移动 原文件夹就不在了 LogPath原始文件,LogMovePath现在文件夹(移动的时候里面的所有文件都随着移动),
//当LogMovePath存在时,则会报错
//如:LogPath=D:\testIo\20190131\Log\
// LogMovePath=D:\testIo\20190132\LogMove\:(20190132这个文件夹必须存在,不然会报错)
// 则会把LogPath的log重命名为LogMove,转移到20190132这个文件夹下面,则20190131中的Log就会删除
Directory.Move(LogPath, LogMovePath); //删除(最底层的文件夹)
//如果LogMovePath为D:\\testIo\\20190132\\LogMove\,则会删除LogMove,如果LogMove里面有内容或者文件夹,需要第二个参数赋值为:true,
//则会把LogMove以及对应的子文件或者文件夹全部删除不然会报错不能删除
LogMovePath = @"D:\testIo\20190132";
Directory.Delete(LogMovePath,true);
}
二:File类的操作类
{
//无论LogPath最后有没有/,最后都会根据需求自动以/隔开的
string fileName = Path.Combine(LogPath, "log.txt");
string fileNameCopy = Path.Combine(LogPath, "logCopy.txt");
string fileNameMove = Path.Combine(LogPath, "logMove.txt");
bool isExists = File.Exists(fileName); //判断文件是否存在
if (!isExists)
{
Directory.CreateDirectory(LogPath);//创建了文件夹之后,才能创建里面的文件
using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入,如果存在则会先删除再重新创建写入)
{
string name = "小伙伴大家好!";
byte[] bytes = Encoding.Default.GetBytes(name);
fileStream.Write(bytes, , bytes.Length);
fileStream.Flush();
}
using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入,如果存在则会先删除再重新创建写入)
{
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine("筒子们大家好!");
sw.Flush();
}
using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入(之前文件如果有内容,则会保留,在后面追加))
{
string msg = "今天我们讨论一下IO操作器!";
sw.WriteLine(msg);
sw.Flush();
}
using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
{
string name = "那让我们一起揭开IO的面纱!";
byte[] bytes = Encoding.Default.GetBytes(name);
sw.BaseStream.Write(bytes, , bytes.Length);
sw.Flush();
}
foreach (string result in File.ReadAllLines(fileName))
{
Console.WriteLine(result);
}
string sResult = File.ReadAllText(fileName); //读取文件的所有内容,得到字符串
Byte[] byteContent = File.ReadAllBytes(fileName); //读取文件的所有内容,得到字节
string sResultByte =Encoding.UTF8.GetString(byteContent); //把字节转换为字符串
using (FileStream stream = File.OpenRead(fileName))//分批读取
{
int length = ;
int result = ;
do
{
byte[] bytes = new byte[length];
result = stream.Read(bytes, , );
for (int i = ; i < result; i++)
{
Console.WriteLine(bytes[i].ToString());
}
}
while (length == result);
}
File.Copy(fileName, fileNameCopy); //文件copy
File.Move(fileName, fileNameMove); //同上面文件夹移动
File.Delete(fileNameCopy); //删除fileNameCopy
File.Delete(fileNameMove);//删除fileNameMove,但是尽量不要delete
}
}
三:DriveInfo类
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
//TotalSize 是字节
if (drive.IsReady)
Console.WriteLine($"类型:{drive.DriveType} 卷标:{drive.VolumeLabel} 名称:{drive.Name} 总空间:{drive.TotalSize} 剩余空间:{drive.TotalFreeSpace}");
else
Console.WriteLine($"类型:{drive.DriveType} is not ready");
}
}
四:Path操作类
{
Console.WriteLine(Path.GetDirectoryName(LogPath)); //返回目录名,需要注意路径末尾是否有反斜杠对结果是有影响的
Console.WriteLine(Path.GetDirectoryName(@"d:\\abc")); //将返回 d:\
Console.WriteLine(Path.GetDirectoryName(@"d:\\abc\"));// 将返回 d:\abc
Console.WriteLine(Path.GetRandomFileName());//将返回随机的文件名
Console.WriteLine(Path.GetFileNameWithoutExtension("d:\\abc.txt"));// 将返回abc
Console.WriteLine(Path.GetInvalidPathChars());// 将返回禁止在路径中使用的字符
Console.WriteLine(Path.GetInvalidFileNameChars());//将返回禁止在文件名中使用的字符
Console.WriteLine(Path.Combine(LogPath, "log.txt"));//合并两个路径Combine文件夹不用关心有没有"/",如果没有会自动添加一个"/"
}
五:最后来一个找到一个文件夹下面找出全部的子文件夹(使用递归)
public class Recursion
{
/// <summary>
/// 找出全部的子文件夹
/// </summary>
/// <param name="rootPath">根目录</param>
/// <returns></returns>
public static List<DirectoryInfo> GetAllDirectory(string rootPath)
{
if (!Directory.Exists(rootPath))
return new List<DirectoryInfo>(); List<DirectoryInfo> directoryList = new List<DirectoryInfo>();//容器
DirectoryInfo directory = new DirectoryInfo(rootPath);//root文件夹
directoryList.Add(directory); return GetChild(directoryList, directory);
} /// <summary>
/// 完成 文件夹--子目录--放入集合
/// </summary>
/// <param name="directoryList"></param>
/// <param name="directoryCurrent"></param>
/// <returns></returns>
private static List<DirectoryInfo> GetChild(List<DirectoryInfo> directoryList, DirectoryInfo directoryCurrent)
{
var childArray = directoryCurrent.GetDirectories();
if (childArray != null && childArray.Length > )
{
directoryList.AddRange(childArray);
foreach (var child in childArray)
{
GetChild(directoryList, child);
}
}
return directoryList;
}
}
思维图如下: 
c# IO操作的更多相关文章
- [.NET] 利用 async & await 进行异步 IO 操作
利用 async & await 进行异步 IO 操作 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6082673.html 序 上次,博主 ...
- 文件IO操作..修改文件的只读属性
文件的IO操作..很多同行的IO工具类都是直接写..但是如果文件有只读属性的话..则会写入失败..所以附加了一个只读的判断和修改.. 代码如下: /// <summary> /// 创建文 ...
- python之协程与IO操作
协程 协程,又称微线程,纤程.英文名Coroutine. 协程的概念很早就提出来了,但直到最近几年才在某些语言(如Lua)中得到广泛应用. 子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B ...
- JAVASE02-Unit08: 文本数据IO操作 、 异常处理
Unit08: 文本数据IO操作 . 异常处理 * java.io.ObjectOutputStream * 对象输出流,作用是进行对象序列化 package day08; import java.i ...
- JAVASE02-Unit07: 基本IO操作 、 文本数据IO操作
基本IO操作 . 文本数据IO操作 java标准IO(input/output)操作 package day07; import java.io.FileOutputStream; import ja ...
- IO操作概念。同步、异步、阻塞、非阻塞
“一个IO操作其实分成了两个步骤:发起IO请求和实际的IO操作. 同步IO和异步IO的区别就在于第二个步骤是否阻塞,如果实际的IO读写阻塞请求进程,那么就是同步IO. 阻塞IO和非阻塞IO的区别在于第 ...
- Java基础复习笔记系列 七 IO操作
Java基础复习笔记系列之 IO操作 我们说的出入,都是站在程序的角度来说的.FileInputStream是读入数据.?????? 1.流是什么东西? 这章的理解的关键是:形象思维.一个管道插入了一 ...
- java中的IO操作总结
一.InputStream重用技巧(利用ByteArrayOutputStream) 对同一个InputStream对象进行使用多次. 比如,客户端从服务器获取数据 ,利用HttpURLConnect ...
- Linux系统编程--文件IO操作
Linux思想即,Linux系统下一切皆文件. 一.对文件操作的几个函数 1.打开文件open函数 int open(const char *path, int oflags); int open(c ...
- Java之IO操作总结
所谓IO,也就是Input与Output的缩写.在java中,IO涉及的范围比较大,这里主要讨论针对文件内容的读写 其他知识点将放置后续章节 对于文件内容的操作主要分为两大类 分别是: 字符流 字节流 ...
随机推荐
- timesten报错:error while loading shared libraries: libaio.so.1: cannot open shared object file : No such file or directory
我遇到的这个错是因为缺少依赖:libaio 直接yum -y install libaio 然后重新安装就OK了
- CentOS 7.3/Linux .net core sdk 安装
执行下列命令,安装.NET Core SDK(微软官方教程地址 https://www.microsoft.com/net/learn/get-started/linuxcentos) 点开链接,选择 ...
- 【C语言】多项式加法(mooc第七周测试题)
这个小题目吧我折磨的够呛,,主要在于特殊情况考虑不周,测试用例老是通不过.. 小结: 做法:用一个数组来存储多项式,用下标表示幂次数,数组元素值表示对应系数 输出特殊格式考虑:系数和幂次数为0,1,- ...
- 反调试——jmp到那个地址
目录 1.前言 2.原理讲解 3.代码实现 前言 这节的反调试是通过构造代码来干扰正常的分析.反调试参考CrypMic勒索病毒 原理讲解 在逆向分析汇编代码时,一般都是通过汇编指令call或jmp跳到 ...
- Git 简单入门(二)
分支管理 分支的作用 提交不完整的代码到主分支上会导致别人不能正常开发 如果等代码全部写完再提交,存在丢失每天进度的风险 详见:https://segmentfault.com/q/101000001 ...
- laravel-elasticsearch 全文搜索设置
1.首先安装 jave环境 jdk 下载地址 ,我用的是最新版本的,有时版本要跟elasticsearch对应 2.安装elasticsearch 下载地址 3.安装Laravel scout 全文搜 ...
- oracle启动服务和监听
1.故障问题:tomcat显示启动oracle数据库失败,数据库服务启动正常 操作1:重启tomcat查看错误信息 2:重启数据库服务 命令: (1) 启动Oracle服务 C:\Users\Admi ...
- python语法_模块_os_sys
os模块:提供对此操作系统进行操作的接口 os.getcwd() 获取python运行的工作目录. os.chdir(r'C:\USERs') 修改当前工作目录. os.curdir 返回当前目录 ( ...
- [Swift]LeetCode55. 跳跃游戏 | Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the arra ...
- [Swift]LeetCode401. 二进制手表 | Binary Watch
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom ...