今天我们主要讨论的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操作的更多相关文章

  1. [.NET] 利用 async & await 进行异步 IO 操作

    利用 async & await 进行异步 IO 操作 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6082673.html  序 上次,博主 ...

  2. 文件IO操作..修改文件的只读属性

    文件的IO操作..很多同行的IO工具类都是直接写..但是如果文件有只读属性的话..则会写入失败..所以附加了一个只读的判断和修改.. 代码如下: /// <summary> /// 创建文 ...

  3. python之协程与IO操作

    协程 协程,又称微线程,纤程.英文名Coroutine. 协程的概念很早就提出来了,但直到最近几年才在某些语言(如Lua)中得到广泛应用. 子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B ...

  4. JAVASE02-Unit08: 文本数据IO操作 、 异常处理

    Unit08: 文本数据IO操作 . 异常处理 * java.io.ObjectOutputStream * 对象输出流,作用是进行对象序列化 package day08; import java.i ...

  5. JAVASE02-Unit07: 基本IO操作 、 文本数据IO操作

    基本IO操作 . 文本数据IO操作 java标准IO(input/output)操作 package day07; import java.io.FileOutputStream; import ja ...

  6. IO操作概念。同步、异步、阻塞、非阻塞

    “一个IO操作其实分成了两个步骤:发起IO请求和实际的IO操作. 同步IO和异步IO的区别就在于第二个步骤是否阻塞,如果实际的IO读写阻塞请求进程,那么就是同步IO. 阻塞IO和非阻塞IO的区别在于第 ...

  7. Java基础复习笔记系列 七 IO操作

    Java基础复习笔记系列之 IO操作 我们说的出入,都是站在程序的角度来说的.FileInputStream是读入数据.?????? 1.流是什么东西? 这章的理解的关键是:形象思维.一个管道插入了一 ...

  8. java中的IO操作总结

    一.InputStream重用技巧(利用ByteArrayOutputStream) 对同一个InputStream对象进行使用多次. 比如,客户端从服务器获取数据 ,利用HttpURLConnect ...

  9. Linux系统编程--文件IO操作

    Linux思想即,Linux系统下一切皆文件. 一.对文件操作的几个函数 1.打开文件open函数 int open(const char *path, int oflags); int open(c ...

  10. Java之IO操作总结

    所谓IO,也就是Input与Output的缩写.在java中,IO涉及的范围比较大,这里主要讨论针对文件内容的读写 其他知识点将放置后续章节 对于文件内容的操作主要分为两大类 分别是: 字符流 字节流 ...

随机推荐

  1. linux 做了raid后,硬盘坏了更换问题

    系统做完raid1后发现 raid盘坏了,硬盘都是热插拔的,更换后,需要简单配置一下才能自动进行镜像拷贝. 在pd mgmt 页面,选择新加入的硬盘,按F2,选择 make global HS选项 选 ...

  2. ionic-基于angularjs实现的多级城市选择组件

    大家都知道在移动端的选择地区组件,大部分都是模拟IOS选择器做的城市三级联动,但是在IOS上比较好,在Android上因为有的不支持ion-scroll.所以就会出现滚动不会自动回滚到某一个的正中间. ...

  3. Java EE 导图

  4. [LeetCode] Hand of Straights 一手顺子牌

    Alice has a hand of cards, given as an array of integers. Now she wants to rearrange the cards into ...

  5. 2018申请淘宝客AppKey

    1.www.alimama.com 申请账号进入后2.进入我的联盟,按下面的步骤 完成以后等待网站审核. 3.审核完成后 按以下的图,申请进入开放平台或得appkey 4.最后就可以进入开放平台申请看 ...

  6. powerdesigner 不能自动生成注释的解决方法(三步解决)

    解决power designer 不能自动生成注释的解决办法只需要3步: 一.快捷键 Ctrl+Shift+X 打开脚本编辑器:(快捷键不能执行的话可以从这个路径执行:Tools --> Exc ...

  7. Lesson 27 A wet night

    Text Late in the afternoon, the boys put up their tent in the middle of a feild. As soon as this was ...

  8. 如何让浏览器支持ES6语法,步骤详细到小学生都能看懂!

    为什么ES6会有兼容性问题? 由于广大用户使用的浏览器版本在发布的时候也许早于ES6的定稿和发布,而到了今天,我们在编程中如果使用了ES6的新特性,浏览器若没有更新版本,或者新版本中没有对ES6的特性 ...

  9. 【RL-TCPnet网络教程】第13章 RL-TCPnet之TCP服务器

    第13章      RL-TCPnet之TCP服务器 本章节为大家讲解RL-TCPnet的TCP服务器实现,学习本章节前,务必要优先学习第12章TCP传输控制协议基础知识.有了这些基础知识之后,再搞本 ...

  10. Redis 设计与实现 (四)--事件、客户端

    事件 一.文件事件 文件事件处理器使用I/O多路复用程序来同时监听多个套接字, 监听套接字,分配对应的处理事件. 四个组成部分:套接字 .I/O多路复用 . 文件事件分派器 . 事件处理器 连接应答处 ...