源自https://www.cnblogs.com/liyangLife/p/4797583.html 谢谢

1.文件系统

(1)文件系统类的介绍
文件操作类大都在System.IO命名空间里。FileSystemInfo类是任何文件系统类的基类;FileInfo与File表示文件系统中的文件;DirectoryInfo与Directory表示文件系统中的文件夹;Path表示文件系统中的路径;DriveInfo提供对有关驱动器的信息的访问。注意,XXXInfo与XXX类的区别是:XXX是静态类,XXXInfo类可以实例化。
还有个较为特殊的类System.MarshalByRefObject允许在支持远程处理的应用程序中跨应用程序域边界访问对象。
(2)FileInfo与File类
class Program
{
static void Main(string[] args)
{
FileInfo file = new FileInfo(@"E:\学习笔记\C#平台\test.txt");//创建文件
Console.WriteLine("创建时间:" + file.CreationTime);
Console.WriteLine("路径:" + file.DirectoryName);
StreamWriter sw = file.AppendText();//打开追加流
sw.Write("李志伟");//追加数据
sw.Dispose();//释放资源,关闭文件
File.Move(file.FullName, @"E:\学习笔记\test.txt");//移动
Console.WriteLine("完成!");
Console.Read();
}
}
(3)DirectoryInfo与Directory类
class Program
{
static void Main(string[] args)
{
//创建文件夹
DirectoryInfo directory = new DirectoryInfo(@"E:\学习笔记\C#平台\test");
directory.Create();
Console.WriteLine("父文件夹:" + directory.Parent.FullName);
//输出父目录下的所有文件与文件夹
FileSystemInfo[] files = directory.Parent.GetFileSystemInfos();
foreach (FileSystemInfo fs in files)
{
Console.WriteLine(fs.Name);
}
Directory.Delete(directory.FullName);//删除文件夹
Console.WriteLine("完成!");
Console.Read();
}
}
(4)Path类
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Path.Combine(@"E:\学习笔记\C#平台", @"Test\Test.TXT"));//连接
Console.WriteLine("平台特定的字符:" + Path.DirectorySeparatorChar);
Console.WriteLine("平台特定的替换字符:" + Path.AltDirectorySeparatorChar);
Console.Read();
}
}
(5)DriveInfo类
class Program
{
static void Main(string[] args)
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
if (d.IsReady)
{
Console.WriteLine("总容量:" + d.TotalFreeSpace);
Console.WriteLine("可用容量:" + d.AvailableFreeSpace);
Console.WriteLine("驱动器类型:" + d.DriveFormat);
Console.WriteLine("驱动器的名称:" + d.Name + "\n");
}
}
Console.WriteLine("OK!");
Console.Read();
}
}
回到顶部
2.文件操作

(1)移动、复制、删除文件
class Program
{
static void Main(string[] args)
{
string path = @"E:\学习笔记\C#平台\Test.txt";
File.WriteAllText(path, "测试数据");
Console.WriteLine("文件已创建,请查看!");
Console.ReadLine();
File.Move(path, @"E:\学习笔记\Test.txt");
Console.WriteLine("移动完成,请查看!");
Console.ReadLine();
File.Copy(@"E:\学习笔记\Test.txt", path);
Console.WriteLine("文件已复制,请查看!");
Console.ReadLine();
File.Delete(path);
File.Delete(@"E:\学习笔记\Test.txt");
Console.WriteLine("文件已删除,请查看!\nOK!");
Console.Read();
}
}
(2)判断是文件还是文件夹
class Program
{
static void Main(string[] args)
{
IsFile(@"E:\学习笔记\C#平台\Test.txt");
IsFile(@"E:\学习笔记\");
IsFile(@"E:\学习笔记\XXXXXXX");
Console.Read();
}
//判断路径是否是文件或文件夹
static void IsFile(string path)
{
if (Directory.Exists(path))
{
Console.WriteLine("是文件夹!");
}
else if (File.Exists(path))
{
Console.WriteLine("是文件!");
}
else
{
Console.WriteLine("路径不存在!");
}
}
}
回到顶部
3.读写文件与数据流

(1)读文件
class Program
{
static void Main(string[] args)
{
string path = @"E:\学习笔记\C#平台\Test.txt";
byte[] b = File.ReadAllBytes(path);
Console.WriteLine("ReadAllBytes读二进制:");
foreach (byte temp in b)
{
Console.Write((char)temp+" ");
}
string[] s = File.ReadAllLines(path, Encoding.UTF8);
Console.WriteLine("\nReadAllLines读所有行:");
foreach (string temp in s)
{
Console.WriteLine("行:"+temp);
}
string str = File.ReadAllText(path, Encoding.UTF8);
Console.WriteLine("ReadAllText读所有行:\n" + str);
Console.Read();
}
}
(2)写文件
class Program
{
static void Main(string[] args)
{
string path = @"E:\学习笔记\C#平台\Test.txt";
File.WriteAllBytes(path,new byte[] {0,1,2,3,4,5,6,7,8,9});//写入二进制
Console.WriteLine("WriteAllBytes写入二进制成功");
Console.ReadLine();
string[] array = {"123","456","7890"};
File.WriteAllLines(path, array, Encoding.UTF8);//写入所有行
Console.WriteLine("WriteAllLines写入所有行成功");
Console.ReadLine();
File.WriteAllText(path, "abcbefghijklmn",Encoding.UTF8);//写入字符串
Console.WriteLine("WriteAllText写入字符串成功\nOK!");
Console.Read();
}
}
(3)数据流
最常用的流类如下:
FileStream: 文件流,可以读写二进制文件。
StreamReader: 流读取器,使其以一种特定的编码从字节流中读取字符。
StreamWriter: 流写入器,使其以一种特定的编码向流中写入字符。
BufferedStream: 缓冲流,给另一流上的读写操作添加一个缓冲层。
数据流类的层次结构:

(4)使用FileStream读写二进制文件
class Program
{
static void Main(string[] args)
{
string path = @"E:\学习笔记\C#平台\Test.txt";
//以写文件的方式创建文件
FileStream file = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
string str = "测试文件--李志伟";
byte[] bytes = Encoding.Unicode.GetBytes(str);
file.Write(bytes, 0, bytes.Length);//写入二进制
file.Dispose();
Console.WriteLine("写入数据成功!!!");
Console.ReadLine();
//以读文件的方式打开文件
file = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] temp = new byte[bytes.Length];
file.Read(temp, 0, temp.Length);//读取二进制
Console.WriteLine("读取数据:" + Encoding.Unicode.GetString(temp));
file.Dispose();
Console.Read();
}
}
(5)StreamWriter与StreamReader
使用StreamWriterStreamReader就不用担心文本文件的编码方式,所以它们很适合读写文本文件。
class Program
{
static void Main(string[] args)
{
string path = @"E:\学习笔记\C#平台\Test.txt";
//以写文件的方式创建文件
FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
sw.WriteLine("测试文件--李志伟");
sw.Dispose();
Console.WriteLine("写入数据成功!!!");
Console.ReadLine();
//以读文件的方式打开文件
file = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
Console.WriteLine("读取数据:"+sr.ReadToEnd());
sr.Dispose();
Console.Read();
}
}
回到顶部
4.映射内存的文件

(1)MemoryMappedFile类(.NET4新增)
应用程序需要频繁地或随机地访问文件时,最好使用MemoryMappedFile类(映射内存的文件)。使用这种方式允许把文件的一部分或者全部加载到一段虚拟内存上,这些文件内容会显示给应用程序,就好像这个文件包含在应用程序的主内存中一样。
(2)使用示例
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmfile = MemoryMappedFile.CreateFromFile(@"E:\Test.txt", FileMode.OpenOrCreate, "MapName", 1024 * 1024);
MemoryMappedViewAccessor view = mmfile.CreateViewAccessor();//内存映射文件的视图
//或使用数据流操作内存文件
//MemoryMappedViewStream stream = mmfile.CreateViewStream();
string str = "测试数据:李志伟!";
int length = Encoding.UTF8.GetByteCount(str);
view.WriteArray<byte>(0, Encoding.UTF8.GetBytes(str), 0, length);//写入数据
byte[] b = new byte[length];
view.ReadArray<byte>(0, b, 0, b.Length);
Console.WriteLine(Encoding.UTF8.GetString(b));
mmfile.Dispose();//释放资源
Console.Read();
}
}
回到顶部
5.文件安全

(1)ACL介绍
ACL是存在于计算机中的一张表(访问控制表),它使操作系统明白每个用户对特定系统对象,例如文件目录或单个文件的存取权限。每个对象拥有一个在访问控制表中定义的安全属性。这张表对于每个系统用户有拥有一个访问权限。最一般的访问权限包括读文件(包括所有目录中的文件),写一个或多个文件和执行一个文件(如果它是一个可执行文件或者是程序的时候)。
(2)读取文件的ACL
class Program
{
static void Main(string[] args)
{
FileStream file = new FileStream(@"E:\Test.txt", FileMode.Open, FileAccess.Read);
FileSecurity filesec = file.GetAccessControl();//得到文件访问控制属性
//输出文件的访问控制项
foreach (FileSystemAccessRule filerule in filesec.GetAccessRules(true, true, typeof(NTAccount)))
{
Console.WriteLine(filerule.AccessControlType + "--" + filerule.FileSystemRights + "--" + filerule.IdentityReference);
}
file.Dispose();
Console.Read();
}
}
(3)读取文件夹的ACL
class Program
{
static void Main(string[] args)
{
DirectoryInfo dir= new DirectoryInfo(@"E:\学习笔记\C#平台");
DirectorySecurity filesec = dir.GetAccessControl();//得到文件访问控制属性
//输出文件的访问控制项
foreach (FileSystemAccessRule filerule in filesec.GetAccessRules(true, true, typeof(NTAccount)))
{
Console.WriteLine(filerule.AccessControlType + "--" + filerule.FileSystemRights + "--" + filerule.IdentityReference);
}
Console.Read();
}
}
(4)修改ACL
class Program
{
static void Main(string[] args)
{
FileStream file = new FileStream(@"E:\Test.txt", FileMode.Open, FileAccess.Read);
FileSecurity filesec = file.GetAccessControl();//得到文件访问控制属性
Print(filesec.GetAccessRules(true, true, typeof(NTAccount)));//输出文件访问控制项
FileSystemAccessRule rule = new FileSystemAccessRule(
new NTAccount(@"CENTER-YFB-512\LiZW"), //计算机账户名
FileSystemRights.Delete, //操作权限
AccessControlType.Allow);//能否访问受保护的对象
filesec.AddAccessRule(rule);//增加ACL项
Print(filesec.GetAccessRules(true, true, typeof(NTAccount)));//输出文件访问控制项
filesec.RemoveAccessRule(rule);//移除ACL项
Print(filesec.GetAccessRules(true, true, typeof(NTAccount)));//输出文件访问控制项
file.Dispose();
Console.Read();
}
//输出文件访问控制项
static void Print(AuthorizationRuleCollection rules)
{
foreach (FileSystemAccessRule filerule in rules)
{
Console.WriteLine(filerule.AccessControlType + "--" + filerule.FileSystemRights + "--" + filerule.IdentityReference);
}
Console.WriteLine("================================================");
}
}
回到顶部
6.读写注册表

(1)注册表介绍
Windows注册表是帮助Windows控制硬件、软件、用户环境和Windows界面的一套数据文件,运行regedit可以看到5个注册表配置单元(实际有7个):
HKEY-CLASSES-ROOT: 文件关联和COM信息
HKEY-CURRENT-USER: 用户轮廓
HKEY-LOCAL-MACHINE: 本地机器系统全局配置子键
HKEY-USERS: 已加载用户轮廓子键
HKEY-CURRENT-CONFIG: 当前硬件配置
(2).NET操作注册表的类
在.NET中提供了Registry类、RegistryKey类来实现对注册表的操作。其中Registry类封装了注册表的七个基本主健:
Registry.ClassesRoot 对应于HKEY_CLASSES_ROOT主键
Registry.CurrentUser 对应于HKEY_CURRENT_USER主键
Registry.LocalMachine 对应于 HKEY_LOCAL_MACHINE主键
Registry.User 对应于 HKEY_USER主键
Registry.CurrentConfig 对应于HEKY_CURRENT_CONFIG主键
Registry.DynDa 对应于HKEY_DYN_DATA主键
Registry.PerformanceData 对应于HKEY_PERFORMANCE_DATA主键
RegistryKey类封装了对注册表的基本操作,包括读取,写入,删除。其中读取的主要函数有: 
OpenSubKey() 主要是打开指定的子键。
GetSubKeyNames() 获得主键下面的所有子键的名称,它的返回值是一个字符串数组。
GetValueNames() 获得当前子键中的所有的键名称,它的返回值也是一个字符串数组。
GetValue() 指定键的键值。
写入的函数:
   CreateSubKey() 增加一个子键
   SetValue() 设置一个键的键值
删除的函数:
   DeleteSubKey() 删除一个指定的子键。
   DeleteSubKeyTree() 删除该子键以及该子键以下的全部子键。
(3)示例
class Program
{
static void Main(string[] args)
{
string path = @"SOFTWARE\Microsoft\Internet Explorer\Extensions";
RegistryKey pregkey = Registry.LocalMachine.OpenSubKey(path, true);//以只读方式
if (pregkey != null)
{
Console.WriteLine(pregkey.Name + "--" + pregkey.SubKeyCount + "--" + pregkey.ValueCount);
string preName = System.Guid.NewGuid().ToString();
pregkey.CreateSubKey(preName);//增加一个子键
RegistryKey new_pregkey = Registry.LocalMachine.OpenSubKey(path + @"\" + preName, true);
new_pregkey.SetValue("姓名", "李志伟");//设置一个键的键值
new_pregkey.SetValue("键名", "值内容");//设置一个键的键值
Console.WriteLine(pregkey.Name + "--" + pregkey.SubKeyCount + "--" + pregkey.ValueCount);
pregkey.Close();
new_pregkey.Close();
}
Console.Read();
}
}
回到顶部
7.读写独立的存储器

(1)IsolatedStorageFile类
使用IsolatedStorageFile类可以读写独立的存储器,独立的存储器可以看成一个虚拟磁盘,在其中可以保存只由创建他们的应用程序或其应用程序程序实例共享的数据项。
独立的存储器的访问类型有两种(如下图):第一种是一个应用程序的多个实例在同一个独立存储器中工作,第二种是一个应用程序的多个实例在各自不同的独立存储器中工作。

(2)示例
class Program
{
static void Main(string[] args)
{
//写文件
IsolatedStorageFileStream storStream = new IsolatedStorageFileStream(@"Test.txt", FileMode.Create, FileAccess.Write);
string str = "测试数据:李志伟!ABCD";
byte[] bs = Encoding.UTF8.GetBytes(str);
storStream.Write(bs, 0, bs.Length);//写数据
storStream.Dispose();
//读文件
IsolatedStorageFile storFile = IsolatedStorageFile.GetUserStoreForDomain();
string[] files=storFile.GetFileNames(@"Test.txt");
foreach (string t in files)
{
Console.WriteLine(t);
storStream = new IsolatedStorageFileStream(t, FileMode.Open, FileAccess.Read);
StreamReader sr=new StreamReader(storStream);
Console.WriteLine("读取文件:"+sr.ReadToEnd());
sr.Dispose();
storFile.DeleteFile(t);//删除文件
}
storFile.Dispose();
Console.WriteLine("OK!");
Console.Read();
}
}
-------------------------------------------------------------------------------------------------------------------------------

C#常用IO流与读写文件 (转)的更多相关文章

  1. C#常用IO流与读写文件

    .文件系统 ()文件系统类的介绍 文件操作类大都在System.IO命名空间里.FileSystemInfo类是任何文件系统类的基类:FileInfo与File表示文件系统中的文件:Directory ...

  2. File类与常用IO流第四章——IO字节流

    一切文件在存储时,都是以二进制数字的形式保存的,都是一个一个字节.无论使用什么样的流对象,底层传输的始终是二进制数据. 字节输出流 OutputStream java.io.OutputStream ...

  3. Java中常用IO流之文件流的基本使用姿势

    所谓的 IO 即 Input(输入)/Output(输出) ,当软件与外部资源(例如:网络,数据库,磁盘文件)交互的时候,就会用到 IO 操作.而在IO操作中,最常用的一种方式就是流,也被称为IO流. ...

  4. java IO流之三 使用缓冲流来读写文件

    原文:http://blog.csdn.net/haluoluo211/article/details/52183219 一.通过BufferedReader和BufferedWriter来读写文件 ...

  5. Java IO流之普通文件流和随机读写流区别

    普通文件流和随机读写流区别 普通文件流:http://blog.csdn.net/baidu_37107022/article/details/71056011 FileInputStream和Fil ...

  6. 16个常用IO流

    在包java.io.*:下 有以下16个常用的io流类: (Stream结尾的是字节流,是万能流,通常的视频,声音,图片等2进制文件, Reader/Writer结尾的是字符流,字符流适合读取纯文本文 ...

  7. java.io几种读写文件的方式

    一.Java把这些不同来源和目标的数据都统一抽象为数据流. Java语言的输入输出功能是十分强大而灵活的. 在Java类库中,IO部分的内容是很庞大的,因为它涉及的领域很广泛:标准输入输出,文件的操作 ...

  8. java IO流实现删除文件夹以及文件夹中的内容

    这篇主要是对IO文件流对文件常用处理中的删除文件夹,平时我们直接删除文件夹既可以删除里面的全部内容. 但是java在实现删除时,只能是文件才会被删除. 所以这里需要定义一个方法,来递归调用方法(递归调 ...

  9. Java 基础(四)| IO 流之使用文件流的正确姿势

    为跳槽面试做准备,今天开始进入 Java 基础的复习.希望基础不好的同学看完这篇文章,能掌握泛型,而基础好的同学权当复习,希望看完这篇文章能够起一点你的青涩记忆. 一.什么是 IO 流? 想象一个场景 ...

随机推荐

  1. postgresql 10 ssl 双向认证

    https://blog.csdn.net/dna911/article/details/82819637

  2. lojround3

    A.绯色 IOI(开端) 首先注意到是完全图,数据范围又很大,肯定要观察一些性质 我们化简一下式子 发现其实是要求simga(xixj)最大 那么结论就很好想了 最大的和次大的第三大的连一起...然后 ...

  3. noi2018d2t1

    题解: ex-crt 学习见https://www.cnblogs.com/Miracevin/p/9254795.html hdu2891 #include <cstdio> #incl ...

  4. Python_str 的内部功能介绍

    float: x.as_integer_ratio():把浮点型转换成分数最简比 x.hex():返回当前值的十六进制表示 x.fromhex():将十六进制字符串转换为浮点型 float与long的 ...

  5. redis 配置文件配置

    redis的配置和使用 redis的配置的分段的 配置段: 基本配置项 网络配置项 持久化相关配置 复制相关的配置 安全相关配置 Limit相关的配置 SlowLog相关的配置 INCLUDES Ad ...

  6. day16 函数的用法:内置函数,匿名函数

    思维导图需要补全 : 一共有68个内置函数: #内置:python自带 # def func(): # a = 1 # b = 2 # print(locals()) # print(globals( ...

  7. 简单的使用Nginx框架搭建Web服务器~

    系统环境Debian 8,内核版本 一.首先来安装nginx服务程序:  1.安装nginx服务需要的相关程序(记得在root权限下操作下面的指令) aptitude install libpcre3 ...

  8. HBase读写数据的详细流程及ROOT表/META表介绍

    一.HBase读数据流程 1.Client访问Zookeeper,从ZK获取-ROOT-表的位置信息,通过访问-ROOT-表获取.META.表的位置,然后确定数据所在的HRegion位置: 2.Cli ...

  9. 【官档整理】Visual Studio 2017 VS2017 中文离线安装包下载

    [官档整理]Visual Studio 2017 VS2017 中文离线安装包下载 转 https://blog.csdn.net/fromfire2/article/details/81104648 ...

  10. 浅析js闭包

    闭包是一个老生常谈的问题,简单概括下闭包的形成的两个条件: 1.定义在函数内部 2.函数内部引用父层作用域变量 举一个最简单的例子: function test() { var a = 1; func ...