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涉及的范围比较大,这里主要讨论针对文件内容的读写 其他知识点将放置后续章节 对于文件内容的操作主要分为两大类 分别是: 字符流 字节流 ...
随机推荐
- MUI消息推送
一.push通过H5+实现 简单实现方式:通过轮询服务器是否有新消息推送过来 mui.plusReady(function() { plus.navigator.closeSplashscreen() ...
- tyflow车撞墙测试
- 用递归方法求n的阶乘
代码: #include<iostream> using namespace std; int fact(int n); int main() { int n; loop: cin > ...
- MS-UAP发布的UWP的个人隐私策略
我们十分重视您的隐私.本隐私声明解释了我们从您那里收集的个人数据内容以及我们将如何使用这些数据. 我们不收集任何与个人信息相关的数据,只收集与本UWP运行相关的数据,如: 产品使用数据:如每个页面的使 ...
- RabbitMQ 集群原理和完善
一.RabbitMQ集群方案的原理 RabbitMQ这款消息队列中间件产品本身是基于Erlang编写,Erlang语言天生具备分布式特性(通过同步Erlang集群各节点的magic cookie来实现 ...
- vs2017开发Node.js控制台程序
1,新建项目 NodejsConsoleApp1 2,在项目的根目录下,添加 sayModule.js 文件 //sayModule.js function Say1Module() { this. ...
- gps 经纬度 转换实际距离
<!doctype html> <html lang="zh-CN"> <head> <meta charset="utf-8& ...
- 用Vue2仿京东省市区三级联动效果
三级联动,随着越来越多的审美,出现了很多种,好多公司都仿着淘宝的三级联动 ,好看时尚,so我们公司也一样……为了贴代码方便,我把写在data里面省市区的json独立了出来,下载贴进去即可用,链接如下 ...
- [Swift]LeetCode71. 简化路径 | Simplify Path
Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", ...
- [Swift]LeetCode485. 最大连续1的个数 | Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1, ...