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涉及的范围比较大,这里主要讨论针对文件内容的读写 其他知识点将放置后续章节 对于文件内容的操作主要分为两大类 分别是: 字符流 字节流 ...
随机推荐
- pta-树种统计
树种统计 (25 分) 随着卫星成像技术的应用,自然资源研究机构可以识别每一棵树的种类.请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比. 输入格式: 输入首先给出正整数N(≤105 ...
- Linux一键安装宝塔控制面板
Linux一键安装宝塔的命令行 yum install -y wget && wget -O install.sh http://download.bt.cn/install/inst ...
- Java后台使用Websocket教程
在开发一个项目的时候使用到了WebSocket协议 什么是WebSocket? WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据.在WebSocket A ...
- 神经网络_线性神经网络 2 (Nerual Network_Linear Nerual Network 2)
1 LMS 学习规则 1.1 LMS学习规则定义 MSE=(1/Q)*Σe2k=(1/Q)*Σ(tk-ak)2,k=1,2,...,Q 式中:Q是训练样本:t(k)是神经元的期望输出:a(k)是神经元 ...
- thinkphp mysql查询结果为什么全是string问题
找到根目录下的thinkphp\library\think\db\Connection.php 文件 // PDO连接参数 protected $params = [ PDO::ATTR_CASE = ...
- SQL Server 创建服务器和数据库级别审计
一.概述 在上一篇文章中已经介绍了审计的概念:本篇文章主要介绍如何创建审计,以及该收集哪些审核规范. 二.常用的审核对象 2.1.服务器审核对象 1.FAILED_LOGIN_GROUP( Audit ...
- 最新Java技术
最近在网上查资料碰到好多没接触过的技术,先汇总在这里备用,以后慢慢吸收 1. JNA JNI的替代品,调用方式比JNI更直接,不再需要JNI那层中间接口,几乎达到Java直接调用动态库 2. Smal ...
- [Swift]LeetCode367. 有效的完全平方数 | Valid Perfect Square
Given a positive integer num, write a function which returns True if num is a perfect square else Fa ...
- [Swift]LeetCode664. 奇怪的打印机 | Strange Printer
There is a strange printer with the following two special requirements: The printer can only print a ...
- 深度学习笔记(七)SSD 论文阅读笔记简化
一. 算法概述 本文提出的SSD算法是一种直接预测目标类别和bounding box的多目标检测算法.与faster rcnn相比,该算法没有生成 proposal 的过程,这就极大提高了检测速度.针 ...