C# 常用 IO 流与读写文件
1. 文件系统 .................................................................................... 2
(1) 文件系统类的介绍 ............................................................ 2
(2) FileInfo 与File 类 ....................................................... 2
(3) DirectoryInfo 与Directory 类 ................................. 2
(4) Path 类 ............................................................................... 2
(5) DriveInfo 类 .................................................................... 2
2. 文件操作 .................................................................................... 3
(1) 移动、复制、删除文件 ................................................... 3
(2) 判断是文件还是文件夹 ................................................... 3
3. 读写文件与数据流 .................................................................... 4
(1) 读文件 ................................................................................. 4
(2) 写文件 ................................................................................. 4
(3) 数据流 ................................................................................. 4
(4) 使用FileStream 读写二进制文件 ................................ 5
(5) StreamWriter 与StreamReader .................................. 5
4. 映射内存的文件 ........................................................................ 5
(1) MemoryMappedFile 类(.NET4 新增) ............................ 5
(2) 使用示例 ............................................................................. 6
5. 文件安全 .................................................................................... 6
(1) ACL 介绍 ............................................................................. 6
(2) 读取文件的ACL ................................................................. 6
(3) 读取文件夹的ACL ............................................................. 6
(4) 修改ACL ............................................................................. 7
6. 读写注册表 ................................................................................ 7
(1) 注册表介绍 ........................................................................ 7
(2) .NET 操作注册表的类 ...................................................... 7
(3) 示例 ..................................................................................... 8
7. 读 写独立的存储器 .................................................................... 8
(1) IsolatedStorageFile 类 .............................................. 8
(2) 示例 ..................................................................................... 8
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();
}
}