C# System.IO和对文件的读写操作
System.IO命名空间中常用的非抽象类
| BinaryReader | 从二进制流中读取原始数据 |
| BinaryWriter | 从二进制格式中写入原始数据 |
| BufferedStream | 字节流的临时存储 |
| Directory | 有助于操作目录结构 |
| DirectoryInfo | 用于对目录执行操作 |
| DriveInfo | 提供驱动信息 |
| File | 有助于文件处理 |
| FileInfo | 用于对文件执行操作 |
| FileStream | 用于文件中任何位置的读写 |
| MemoryStream | 用于随机访问存储在内存中的数据流 |
| Path | 对路径信息执行操作 |
| StreamReader | 从字节流中读取数据 |
| StreamWriter | 用于向一个流中写入字符 |
| StringWriter | 用于读取字符串缓冲区 |
| StringReader | 用于写入字符串缓冲区 |
FileStream类:
FileStream f = new FileStream("ont.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
| FileMode表示打开的方式 |
|
| FileAccess表示用来读/写和读/写权限 | 操作的模式有:read、Write、readwrite |
| FileShare类似文件锁的东西 |
|
代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
/*
* ================ Path ===============
string file = @"D:\a\b\c\one.txt";
Console.WriteLine(Path.GetDirectoryName(file)); // 获取文件的路径
Console.WriteLine(Path.GetExtension(file)); // 获取文件扩展名
Console.WriteLine(Path.GetFileName(file)); // 获取文件名(包含扩展)
Console.WriteLine(Path.GetFullPath("123.txt")); // 可以根据相对路径获取全路径
Console.WriteLine(Path.GetRandomFileName()); // 随即返回一个文件名(不重复的文件名)
Console.WriteLine(Path.GetTempPath()); // 返回一个临时目录
Console.ReadKey();
*/
/*
* ========================= File ===============================
string logName = "delete.txt"; // 文件名
string filePath = Path.GetFullPath(logName); // 获取全路径
if (!File.Exists(filePath))
{
// 如果文件不存在
File.Create(filePath).Close(); // 创建文件并且关闭
}
// 读取还可以使用 File.ReadAllLines(filePath)按行读取
string logtext = File.ReadAllText(filePath); // 读取文件
Console.WriteLine(logtext);
logtext += "\r\n" + DateTime.Now.Date;
Console.WriteLine(filePath);
File.WriteAllText(filePath, logtext); // 将内容写进文本
Console.ReadKey();
*/
/*
* ======================= FileInfo ==============================
string fileName = "delete.txt";
string filePath = Path.GetFullPath(fileName);
FileInfo fi = new FileInfo(fileName); // 创建管理文件的软连接
if (!fi.Exists)
{
Console.WriteLine("文件不存在!!!");
}
var writeThing = fi.AppendText(); // 追加方式
writeThing.WriteLine(DateTime.Now.ToString()); // 追加文本
writeThing.Close(); // 关闭
var readThing = fi.OpenText(); // 读取
Console.WriteLine(readThing.ReadToEnd());
readThing.Close(); // 关闭
Console.ReadKey();
*/
/*
* ================================== Directory ===========================================
string filePath = @"F:\下载\C#完整版.NET教程(价值398元)\04NetFramework\【IT教程网】04NetFramework\Day02";
string fileP = filePath + @"\abc";
if (!Directory.Exists(fileP))
{
// 判断文件是否存在,如果文件不存在那么创建文件目录
Directory.CreateDirectory(fileP);
}
foreach(var item in Directory.GetFiles(filePath)){
Console.WriteLine(item); // 输出该文件下的子文件名称
}
Console.WriteLine("\r\n");
foreach(var item in Directory.GetDirectories(filePath))
{
Console.WriteLine(item); // 输出该目录下的子目录
}
Console.WriteLine(Directory.GetParent(filePath)); // 返回父类目录
Console.ReadKey();
*/
/*
* ======================== DirectoryInfo ================================
string filePath = @"F:\下载\C#完整版.NET教程(价值398元)\04NetFramework\【IT教程网】04NetFramework\Day02";
DirectoryInfo dir = new DirectoryInfo(filePath);
dir.CreateSubdirectory(@"ab\cd\ef\gh\kj"); // 可连续创建
foreach (var item in dir.GetDirectories())
{
Console.WriteLine(item); // 输出当前文件夹子目录
}
Console.WriteLine("\n");
foreach(var item in dir.GetDirectories())
{
Console.WriteLine(item); // 输出当前文件夹子目录
}
Console.ReadKey();
*/
/*
* ================================== DriveInfo =================================
// 对磁盘进行操作
foreach(DriveInfo item in DriveInfo.GetDrives())
{
Console.WriteLine(item); // 获取所有驱动的名称(显示磁盘的数量)
Console.WriteLine(item.DriveType); // 获取类型
if (item.IsReady)
{
// 判断磁盘是否准备就绪
Console.WriteLine(item.DriveFormat); // 获取存储格式
Console.WriteLine(item.TotalSize); // 获取磁盘大小,默认是比特单位
Console.WriteLine((item.TotalSize * 1.0) / (1024.0*1024.0*1024.0)); // 单位转换,KB/M/G
Console.WriteLine((item.TotalFreeSpace * 1.0) / (1024.0 * 1024.0 * 1024.0)); // 剩余可用路径,这里转换为G
}
Console.WriteLine();
}
Console.ReadKey();
*/
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
// 文件系统的监控 FileSystemWatcher
FileSystemWatcher watcher = new FileSystemWatcher(@"F:\下载\C#完整版.NET教程(价值398元)\04NetFramework\【IT教程网】04NetFramework\Day02"); // 监听该目录
watcher.NotifyFilter = (NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName); // 设置过滤器,LastAccess上一次打开的日期,LastWrite最后一次修改,FileName/DirectoryName文件名或者目录名的修改
// 事件的注册
watcher.Changed += new FileSystemEventHandler(OnChanged); // 监听改变事件,函数OnChanged里面的事件
watcher.Created += new FileSystemEventHandler(OnChanged); // 监听创建事件,函数OnChanged里面的事件
watcher.Deleted += new FileSystemEventHandler(OnChanged); // 监听删除事件,函数OnChanged里面的事件
watcher.Renamed += new RenamedEventHandler(OnRenamed); // 监听重命名事件,函数OnChanged里面的事件
watcher.Error += new ErrorEventHandler(OnError); // 监听错误事件,函数OnError里面的事件
watcher.EnableRaisingEvents = true; // 启用组件
Console.WriteLine("Press 'Enter' to exit...");
Console.ReadKey();
}
// OnChanged事件
private static void OnChanged(object source, FileSystemEventArgs e)
{
WatcherChangeTypes changeType = e.ChangeType; // 获取发生的类型
// e.FullPath获取文件路径及其文件名
Console.WriteLine("The File {0}=>{1}", e.FullPath, changeType.ToString());
}
// OnRenamed事件
private static void OnRenamed(object source, RenamedEventArgs e)
{
WatcherChangeTypes changeType = e.ChangeType;
// e.OldFullPath 获取改变前文件路径及其文件名
Console.WriteLine("The File {0} {2} to {1}", e.OldFullPath, e.FullPath, changeType.ToString());
}
private static void OnError(object source, ErrorEventArgs e)
{
Console.WriteLine("An error has occurred.");
}
}
}
对文件的读写操作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
// 不常用(实际不会这样子用)
/*
// 使用FileStream类来管理文件数据
string overview = "Most commercial application, such as..."; // 定义写入的字符串
FileInfo fileStore = new FileInfo("123.txt"); // 打开对应的文件,默认当前路径
FileStream conduit = fileStore.Create(); // 创建
byte[] encodedOverview = new UTF8Encoding(true).GetBytes(overview); // encodedOverview数组格式的,将其进行编码
conduit.Write(encodedOverview, 0, encodedOverview.Length); // 将编码后的内容(第一个参数固定式byte数组)写进去,需要传递从那个位置开始,多长
conduit.Close(); // 关闭
*/
//
/*
// 使用MemoryStream类来管理内存数据
byte[] overview = new UTF8Encoding(true).GetBytes("Most commercial application, such as..."); // 同样编码字符串
MemoryStream conduit = new MemoryStream(overview.Length); // 开辟内存空间
conduit.Write(overview, 0, overview.Length); // 进行写入,起始位置,长度
Console.WriteLine(conduit.Position.ToString()); // 获取写入指针的当前位置
conduit.Flush(); // 缓存的数据写进内存空间
conduit.Seek(0, SeekOrigin.Begin); // 将文件指正写入到首部
// 读取
byte[] overviewRead = new byte[conduit.Length]; // 创建内存流
conduit.Read(overviewRead, 0, ((int)conduit.Length)); // 读取,从0开始读取,读取长度为((int)conduit.Length)
Console.WriteLine(new UTF8Encoding().GetChars(overviewRead));
conduit.Close();
*/
//
/*
// 使用BufferedStream来提高流性能
string overview = "Most commercial application, such as..."; // 字符串
FileInfo fileStore = new FileInfo("123.txt"); // 打开文件
FileStream conduit = fileStore.Create(); // 创建
BufferedStream fileBuffer = new BufferedStream(conduit); // 创建缓冲区
byte[] encodedOverview = new UTF8Encoding(true).GetBytes(overview); // 编码内容
fileBuffer.Write(encodedOverview, 0, encodedOverview.Length); // 写进缓冲区
fileBuffer.Close(); // 关闭缓冲区
conduit.Close(); // 关闭文件流
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 常用(简便)
//
// 两大分类: 二进制文件、文本文件
// 二进制文件区分BinaryReader/BinaryWriter
// 文本文件又分为:文件、字符串。区分:StringReader/StringWriter
//
// 下面的文本文件读取
/*
// 不使用数据库和文件的情况下存储字符串
StringBuilder sb = new StringBuilder();
TextWriter tw = new StringWriter(sb);
// 写内容(支持多种重载)
tw.Write("您好,");
tw.Write(123);
tw.Write("\tData:{0}\t", DateTime.Now);
tw.WriteLine("bye!");
// 读取操作
TextReader tr = new StringReader(sb.ToString()); // 注意传递进去的是字符串
Console.WriteLine(tr.ReadToEnd()); // 读取
Console.ReadKey();
*/
//
/*
// 对文件进行操作
TextWriter tw = new StreamWriter("123.txt"); // 读取当前路径下的文件
// 写入同上
tw.Write("您好,");
tw.Write(123);
tw.Write("\tData:{0}\t", DateTime.Now);
tw.WriteLine("bye!");
tw.Close(); // 关闭
// 读取
TextReader tr = new StreamReader("123.txt");
Console.WriteLine(tr.ReadToEnd());
// 下面是二进制的
Stream sm = new FileStream("456.dat", FileMode.OpenOrCreate); // 如果文件存在就打开文件,如果文件不存在那么创建并打开文件
BinaryWriter bw = new BinaryWriter(sm);
bw.Write(true);
bw.Write(123);
bw.Write("hello");
bw.Close();
sm.Close();
// 读取
BinaryReader sr = new BinaryReader(new FileStream("456.dat", FileMode.Open));
bool b = sr.ReadBoolean(); // 读取bool
int i = sr.ReadInt32(); // 读取整型
string s = sr.ReadString(); // 读取字符串
Console.WriteLine("bool值:{0},整型:{1},字符型:{2}", b, i, s);
Console.ReadKey();
sr.Close();
// 注:值得注意的是二进制的读写一定要保持他们的顺序,不然会报错
*/
}
}
}
2019-8-3
/*
* 用户: NAMEJR
* 日期: 2019/8/3
* 时间: 19:52
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms; namespace 文件读取
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
} // 文件读取
void Btn_ReadFileClick(object sender, EventArgs e)
{
// OpenFileDialog 打开文件对话框
OpenFileDialog ofd = new OpenFileDialog();
// ShowDialog:模态显示,显示时独占进程(不允许其它窗口显示),当窗口关闭,后续代码才会继续运行
// Show:非模态显示,可以和其它窗口互相切换,后续代码不会停留
if(ofd.ShowDialog()!= DialogResult.OK)
{
return;
}
//this.TB_Content.Text=File.ReadAllText(ofd.FileName,Encoding.Default);
FileStream fs = new FileStream(ofd.FileName,FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(fs,Encoding.Default);
/*
while(!sr.EndOfStream)
{
this.TB_Content.Text += sr.ReadLine(); // 单行读取
}*/
this.TB_Content.Text = sr.ReadToEnd(); // 全部输出
} // 文件保存
void Btn_SaveFileClick(object sender, EventArgs e)
{
// SaveFileDialog 保存文件对话框
SaveFileDialog sfd = new SaveFileDialog();
if(sfd.ShowDialog()!=DialogResult.OK)
{
return;
}
//File.WriteAllText(sfd.FileName,this.TB_Content.Text,Encoding.Default);
StreamWriter sw = new StreamWriter(sfd.FileName,true,Encoding.Default); // 第二个参数为true表示不覆盖(追加)
sw.Write(this.TB_Content.Text);
sw.Flush();
}
}
}
一句话写入:File.WriteAllText("D:/Code/Demo/Demo/upload/index.html", l_strXml);
AddBy 2019-10-24
using System;
using System.IO; namespace 控制台
{
class Program
{
static void Main(string[] args)
{
string l_strPath = @"D:\文件资源\1.xlsx"; // 使用ReadAllText可以进行一次性读取出文档内容,并且指定编码
//Console.WriteLine(File.ReadAllText(l_strPath, Encoding.GetEncoding("GB2312")));
//
// 使用ReadToEnd
FileStream l_fileStream = new FileStream(l_strPath, FileMode.Open);
StreamReader l_streamReader = new StreamReader(l_fileStream);
Console.WriteLine(l_streamReader.ReadToEnd()); // 也可以判断状态
Console.ReadKey();
}
}
}
EndAddBy 2019-10-24
C# System.IO和对文件的读写操作的更多相关文章
- 【等待事件】等待事件系列(3+4)--System IO(控制文件)+日志类等待
[等待事件]等待事件系列(3+4)--System IO(控制文件)+日志类等待 1 BLOG文档结构图 2 前言部分 2.1 导读和注意事项 各位技术爱好者,看完本文后,你可 ...
- android报错及解决2--Sdcard进行文件的读写操作报的异常
报错描述: 对Sdcard进行文件的读写操作的时候,报java.io.FileNotFoundException: /sdcard/testsd.txt (Permission denied),在往S ...
- C# 运用StreamReader类和StreamWriter类实现文件的读写操作
对文件的读写操作应该是最重要的文件操作,System.IO命名空间为我们提供了诸多文件读写操作类,在这里我要向大家介绍最常用也是最基本的StreamReader类和StreamWriter类.从这两个 ...
- 使用字符流(Writer、Reader)完成对文件的读写操作
字符流 字符输出流:Writer,对文件的操作使用子类FileWriter 字符输入流:Reader,对文件的操作使用子类FileReader 每次操作的是一个字符 文件字符操作流会自带缓存,默认大小 ...
- Java 对不同类型的数据文件的读写操作整合器[JSON,XML,CSV]-[经过设计模式改造](2020年寒假小目标03)
日期:2020.01.16 博客期:125 星期四 我想说想要构造这样一个通用文件读写器确实不容易,嗯~以后会添加更多的文件类型,先来熟悉一下文件内容样式: <?xml version=&quo ...
- java io流 对文件夹的操作
java io流 对文件夹的操作 检查文件夹是否存在 显示文件夹下面的文件 ....更多方法参考 http://www.cnblogs.com/phpyangbo/p/5965781.html ,与文 ...
- INI 文件的读写操作
在C#中对INI文件进行读写操作,在此要引入using System.Runtime.InteropServices; 命名空间,具体方法如下: #region 变量 private static r ...
- Android 对 properties文件的读写操作
-. 放在res中的properties文件的读取,例如对放在assets目录中的setting.properties的读取:PS:之所以这里只是有读取操作,而没有写的操作,是因为我发现不能对res下 ...
- java文件的读写操作
java文件的读写操作主要是对输入流和输出流的操作,由于流的分类很多,所以概念很容易模糊,基于此,对于流的读写操作做一个小结. 1.根据数据的流向来分: 输出流:是用来写数据的,是由程序(内存)--- ...
随机推荐
- ionic调用手机系统的拨打电话
android调用如下: 在config.xml中添加 <access origin="tel:*" launch-external="yes" /> ...
- python学习(六)
- 『PyTorch』第五弹_深入理解Tensor对象_下:从内存看Tensor
Tensor存储结构如下, 如图所示,实际上很可能多个信息区对应于同一个存储区,也就是上一节我们说到的,初始化或者普通索引时经常会有这种情况. 一.几种共享内存的情况 view a = t.arang ...
- 【转】在.net Core 中像以前那样的使用HttpContext.Current
1.首先我们要创建一个静态类 public static class MyHttpContext { public static IServiceProvider ServiceProvider; p ...
- redis可执行文件说明
redis-server :redis服务器 redis-cli :redis命令客户端 redis-benchmark :redis性能压测工具 redis-check-dump ...
- Vue(二) 计算属性
模板内的表达式常用于简单的运算,当过长或逻辑复杂时,难以维护,计算属性就是解决该问题的 什么是计算属性 表达式如果过长,或逻辑更为复杂,就会变得臃肿甚至难以维护,比如: <div> {{ ...
- 企业面试题:Buffer与cache的区别?
buffer缓冲 cache是缓存. 写缓冲,读缓存.简单点说,buffer是即将要被写入磁盘的,而cache是被从磁盘中读出来的.缓冲(buffers)是根据磁盘的读写设计的,把分散的写操作集中进行 ...
- Java中的值传递与引用传递
1.基本类型和引用类型在内存中的保存 Java中数据类型分为两大类,基本类型和对象类型.相应的,变量也有两种类型:基本类型和引用类型. 基本类型的变量保存原始值,即它代表的值就是数值本身: 而引用类型 ...
- Linux之expr命令详解
expr命令: expr命令是一个手工命令行计数器,用于在UNIX/LINUX下求表达式变量的值,一般用于整数值,也可用于字符串. –格式为: expr Expression(命令读入Expressi ...
- css图形——三角形
1.css图形简介 在浏览网页的时候,我们经常看见各种图形的效果,而但凡涉及到图形效果,我们第一个想到的就是用图片来实现.但是在前端开发中,为了网站的性能速度,我们都是秉承着少用图片的原生质. 因为图 ...