一, 管理文件系统
文件系统包括Filedirectory Path FileInfo DirectoryInfo DriveInfo类,这些类的对应关系图:
1,File directory 是静态类,如果只是调用一个文件或文件夹的一次操作,可以使用这些类。
FileInfo DirectoryInfo是密封类,需要实例化,所以如果多次操作某个文件可以使用这些类。
2,FileInfo 可以执行Open(),OpenRead(),OpenText(),OpenWrite(),Create(),CraetText()方法,他们返回流对象。
3,path类是一个静态类,不能实例化。
4,file和directory的方法:MoveTo() Delete() CopyTo()
5,读取驱动器信息使用DriveInfo()
二,读写文件
File.ReadAllText(FilePaht)
File.ReadAll(FillPath,Encoding)
File.ReadAllBytes()
File.WriteAll(FilePath,content)
File.WriteAll(FilePath,content,Endcoding)
File.WriteAllBytes()
三,流
1,流的数据源可以是文件,可以是网络,可以是管道,可以使内存。其中System.IO.MemoryStream 和System.IO.Sockets.NetwordkStream来分别处理内存和网络的读写。
2,对于文件的读写,最常用的类是两个 FileSteam和StreamReader与SteamWriter
3,如果要读写缓存的流,则需要写一个继承自BufferSteam的类
4,读写二进制文件首先要实例化FileSteam,两种方法,一种是new,另一种是使用FileSteam fs = file.OpenRead()或file.OpenWrite()或file.Creat()或file.Open() ,使用完以后要Close().
5,ReadByte()会只读出一个byte并变成int。
6,SteamReader和SteamWriter特别适合文本文件的读写,这两个类的方法ReadLine()和WriteLine()
7,streamReader 是将一个文件读成这种形式,然后可以使用sr.ReadLine()一行一行的读,可以使用sr.Read()来读取一个字符或者用ReadToEnd()将剩余字符串全部读出。
8,StreamWriter是一个将要写入的文件变成这种形式,然后使用sw.Write()来填充,最后close()。
各种流对象的对应关系图:
五:文件的安全性
ACL 访问控制表
GetAccessControl:返回一个目录\文件的Windows ACL作为一个DirectorySecurity对象。
SetAccessControl:将DirectorySecurity\FileSecurity对象的ACl入口赋予指定目录。
RemoveAccessControl:去掉某ACL控制
DirectorySecurity: 类定义了如何对目录访问进行审计。该类是潜在的Windows文件安全系统(System.Security.AccessControl命名空间的一部分)的一个抽象。
FileSecurity: 类定义了如何对文件访问进行审计。该类是潜在的Windows文件安全系统(System.Security.AccessControl命名空间的一部分)的一个抽象。
FileSystemAccessRule类代表一个潜在的访问控制入口的抽象,访问控制入口用来指定用户账号,提供的访问类型(读、写等等)以及是许可或拒绝某个权限。同时,该类还指定了如何将访问规则传递给子对象。
FileSystemAuditRule类代表了为某个文件或目录定义审计规则的ACE。
相关操作参考:
http://msdn.microsoft.com/zh-cn/library/system.security.accesscontrol.filesystemsecurity.aspx
六:读写注册表
1.,注册表简介:注册表有7个注册表巢,使用regedit能看到5个。
HKEY_CLASSES_ROOT(HKCR)包含系统上文件类型的细节,以及应用程序可以打开的文件类型。还包括了所有com组件的注册信息。
HKEY_CURRENT_USER(HKCU) 包括用户目前登陆的机器的用户配置。包含桌面设置,环境变量,网络和打印连接和其他用户操作环境的设置。
HKEY_LOCAL_MACHINE(HKLM)是一个很大的巢,包含所有安装在计算机上的软件和硬件信息,这些设置不是用户特有的,而是可用于登陆到机器上的用户。它还包含HKCR巢,HKCR实际上不是一个独立的巢,他只是一个对注册表项HKLM/SOFTWARE/Classes的方便映射。
HKEY_USERS(HKUSR)包含所有用户的用户配置。它包含HKCU巢,HKCU巢是对HKEY_USERS中一个键的映射。
HKEY_CURRENT_CONFIG(HKCF) 包含机器上硬件的信息。
其余两个键包含临时信息,经常会改动。
HKCY_DYN_DATA是一个一般容器,包含需要存储在注册表中的违规数据。
HKEY_PERFORMANCE_DATA 包含与运行应用程序的性能相关的信息。
2.Registry and RegistryKey.
RegistryKey用的最多可以完成对注册表项的所有操作,包含设置键的安全级别。
Registry只能对注册表键进行单一的访问,执行简单操作。另一个作用是提供顶级键的实例。
Registry是通过静态属性来提供这些实例的,这些属性有7个,分别是ClassesRoot、CurrentConfig、CurrentUser、DynData、LocalMechine、PerformanceData和Users。
比如:
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftware =hklm.Openkey("Software");
创建key需要使用CreatSubKey()
删除key需要使用Delete()
获取和设置属性使用GetValue()和SetValue()
使用完成后关闭键Close()
七:独立存储器IsolatedStorageFile
可以看做是一个虚拟硬盘,其中可以保存只能由创建他们的应用程序或与其他应用程序实例共享的数据项。
有两种访问方式:一种是由用户和程序集访问。它可以由多个应用程序实例访问。另一种是由用户、程序集和域来访问。这种访问时,每个应用程序实例都在它自己的独立存储器中工作。
八、实例
//使用FileStream类读写文件
class RWFile
{
public void WriteFile()
{
byte [] m_bDataWrite=new byte[100];
char[] m_cDataWrite = new char[100];
//创建d:\file.txt的FileStream对象
FileStreamm_FilesStream = new FileStream(@"d:\file.txt", FileMode.OpenOrCreate);
try
{
//将要写入的字符串转换成字符数组
m_cDataWrite= "MyFirst File Operation".ToCharArray();
Encoder m_Enc = Encoding.UTF8.GetEncoder();
//通过UTF-8编码将字符数组转换成字节数组
m_Enc.GetBytes(m_cDataWrite,0, m_cDataWrite.Length,m_bDataWrite, 0, true);
//设置流的当前位置为文件开始位置
m_FilesStream.Seek(0, SeekOrigin.Begin);
//将字节数组中的内容写入文件
m_FilesStream.Write(m_bDataWrite,0,m_bDataWrite.Length);
}
catch (IOException e)
{
Console.WriteLine(e.Message);
return;
}
finally
{
m_FilesStream.Close();
}
}
public void ReadFile()
{
byte[] m_bDataRead = new byte[100];
char[] m_cDataRead = new char[100];
//创建d:\file.txt的FileStream对象
FileStreamm_FilesStream = new FileStream(@"d:\file.txt", FileMode.Open);
try
{
//设置流的当前位置为文件开始位置
m_FilesStream.Seek(0, SeekOrigin.Begin);
//将文件内容读入到字节数组中
m_FilesStream.Read(m_bDataRead,0, m_bDataRead.Length);
}
catch (IOException e)
{
Console.WriteLine(e.Message);
return;
}
finally
{ m_FilesStream.Close(); }
Decoder m_Dec = Encoding.UTF8.GetDecoder();
//通过UTF-8编码将字节数组转换成字符数组
m_Dec.GetChars(m_bDataRead,0, m_bDataRead.Length,m_cDataRead,0);
Console.WriteLine(m_cDataRead);
}
}
StreamWriter/StreamReader类读写文件比FileStream更为方便,无需额外的数据类型转换操作
StreamWriter/StreamReader读写文件
//使用StreamWriter/StreamReader类读写文件
class RWFile
{
public void WriteFile()
{
//追加写入方式打开文件
StreamWriter m_SW = new StreamWriter(@"d:\file.txt",true);
//将要写入的字符串转换成字符数组
m_SW.WriteLine("StreamWriter write this file");
m_SW.Close();
}
public void ReadFile()
{
StreamReader m_SW = new StreamReader(@"d:\file.txt");
string m_Data = m_SW.ReadToEnd();
Console.WriteLine(m_Data);
m_SW.Close();
}
}
BinaryWriter/BinaryReader以二进制将基元类型写入流,并支持用特定的编码写入字符串。输出文件需用查看16进制的阅读器才能正确阅读。
BinaryWriter/BinaryReader类读写文件
//使用BinaryWriter/BinaryReader类读写文件
class RWFile
{
public void WriteFile()
{
//追加写入方式打开文件
FileStream m_FS = new FileStream(@"d:\file.txt",FileMode.Append);
BinaryWriter m_BW = new BinaryWriter(m_FS);
for (int i = 0; i < 11; i++)
{m_BW.Write(i);}
m_BW.Close();
m_FS.Close();
}
public void ReadFile()
{
FileStream m_FS = new FileStream(@"d:\file.txt", FileMode.Open, FileAccess.Read);
BinaryReader m_BR = new BinaryReader(m_FS);
for (int i = 0; i < 11; i++)
{Console.WriteLine(m_BR.ReadInt32());}
m_BR.Close();
m_FS.Close();
}
}
FileSystemWatcher可用于监视文件的操作
FileSystemWatcher监视文件变化
class Program
{
static void Main(string[] args)
{
WatcheFile watchFile = new WatcheFile();
while (true)
{
watchFile.WatchFile();
//有个问题,事件会被多次触发,待解决??
System.Threading.Thread.Sleep(10000);
}
}
}
//使用FileSystemWatcher类监视文件改变
class WatcheFile
{
public void WatchFile()
{
FileSystemWatcher watcher = new FileSystemWatcher(@"d:\");
watcher.Changed +=new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
watcher.Renamed+=new RenamedEventHandler(watcher_Renamed);
watcher.EnableRaisingEvents = true;
}
voidwatcher_Changed(object sender,FileSystemEventArgs e)
{
Console.WriteLine(e.Name +"改变了");
}
voidwatcher_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + "创建了");
}
voidwatcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + "删除了");
}
voidwatcher_Renamed(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + "改名了");
}
}
异步IO:
应用异步IO适用于对大型文件的读写操作,它的步骤是:
a.自定义一个无返回值的方法,此方法须接受一个IAsyncResult类型的接口做参数
b.声明一个AsynCallBack代理类型,以上面自定义的方法名称为参数
c.引用方法BeginRead读取文件或BeginWrite写操作
d.在自定义方法中使用方法EndRead取得BeginRead所读取的字节数组
e.BeginRead和BeginWrite的第四参数指定异步IO完成时调用的方法,最后一个参数为状态对象,设为null即可
异步写操作
class AsynchronousIO
{
FileStream myFileStream;
double lngNumber = 100000000;
static void Main(string[] args)
{
AsynchronousIO myAsynchronousIO = new AsynchronousIO();
myAsynchronousIO.longProcessWrite();
Console.Read();
}
public voidlongProcessWrite()
{
byte[] b = new byte[100000000];
for (int i = 0; i < lngNumber;i++) { b[i] = (byte)i; }
Console.WriteLine("写入大量数据....");
AsyncCallback myAsnycCallback = new AsyncCallback(WriteEnd);
myFileStream = new FileStream(@"c:\tnt.txt", FileMode.Create);
//执行到BeginWrite后,不会等待,而是继续往下执行。
//当异步IO完成后,委托实例myAsnycCallback所关联的方法WriteEnd被调用
myFileStream.BeginWrite(b, 0, b.Length,myAsnycCallback, null);
Console.WriteLine("正在将大量数据写入" + @"c:\tnt.txt!");
}
public voidWriteEnd(IAsyncResult asyncResult)
{
Console.WriteLine("文件写入完毕!");
}
}
隔离存储:允许根据不同用户、组件或安全级别存放数据
class StorageMaintain
{
static void Main(string[] args)
{
IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetStore
(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream isFile1 = new IsolatedStorageFileStream
("isFile1.bin", FileMode.Create, myIsoStore);
IsolatedStorageFileStream isFile2 = new IsolatedStorageFileStream
("isFile2.txt", FileMode.Create, myIsoStore);
IsolatedStorageFileStream isFile3 = new IsolatedStorageFileStream
("isFile3.txt", FileMode.Create, myIsoStore);
myIsoStore.CreateDirectory("ISDRoot");
myIsoStore.CreateDirectory("ISDRoot2");
myIsoStore.CreateDirectory("ISDRoot/subISDRoot");
myIsoStore.CreateDirectory("ISDRootSecond");
IsolatedStorageFileStream isFile4 = new IsolatedStorageFileStream
("ISDRoot/rootFile1.txt", FileMode.Create, myIsoStore);
IsolatedStorageFileStream isFile5 = new IsolatedStorageFileStream
("ISDRoot/subISDRoot/rootFile2.txt", FileMode.Create, myIsoStore);
IsolatedStorageFileStream isFile6 = new IsolatedStorageFileStream
("ISDRoot/subISDRoot/rootFile3.txt", FileMode.Create, myIsoStore);
IsolatedStorageFileStream isFile7 = new IsolatedStorageFileStream
("ISDRootSecond/rootFile4.txt", FileMode.Create, myIsoStore);
isFile1.Close();
isFile2.Close();
isFile3.Close();
isFile4.Close();
isFile5.Close();
isFile6.Close();
isFile7.Close();
//在隔离存储区读写操作
IsolatedStorageFileStream isFile2_W = newIsolatedStorageFileStream
("isFile2.txt", FileMode.Open, myIsoStore);
StreamWriter myWriter = new StreamWriter(isFile2_W);
myWriter.WriteLine("This is a test");
myWriter.Close();
isFile2_W.Close();
IsolatedStorageFileStream isFile2_R = new IsolatedStorageFileStream
("isFile2.txt", FileMode.Open, myIsoStore);
StreamReader myReader = new StreamReader(isFile2_R);
Console.WriteLine(myReader.ReadLine());
isFile2_R.Close();
myReader.Close();
myIsoStore.Close();
myIsoStore = IsolatedStorageFile.GetStore
(IsolatedStorageScope.User|IsolatedStorageScope.Assembly,null,null);
Console.WriteLine("列出根目录下扩展名为bin的文件!");
foreach (string filename inmyIsoStore.GetFileNames("*.bin"))
{
Console.WriteLine(filename);
}
Console.WriteLine("====================");
Console.WriteLine("列出根目录下所有文件!");
foreach (string filename inmyIsoStore.GetFileNames ("*"))
{
Console.WriteLine(filename);
}
Console.WriteLine("====================");
Console.WriteLine("列出根目录及子目录下的所有文件!");
foreach (string directory in myIsoStore.GetDirectoryNames ("*"))
{
Console.WriteLine(directory);
foreach (string filename in myIsoStore.GetFileNames(directory+"/*"))
{
Console.WriteLine("\t"+filename);
}
foreach (string sdirectory in myIsoStore.GetDirectoryNames (directory+"/*"))
{
Console.WriteLine(directory+"/"+sdirectory);
foreach (string filename inmyIsoStore.GetFileNames(directory +"/"+sdirectory+"/*"))
{
Console.WriteLine("\t"+filename);
}
}
}
myIsoStore.DeleteFile("isFile1.bin");
myIsoStore.DeleteDirectory("ISDRoot2");
myIsoStore.Close ();
Console.Read();
}
}
使用DirectorySecurity 类将访问控制列表 (ACL) 项添加到目录中,然后将它从目录中移除。
using System;
using System.IO;
using System.Security.AccessControl;
namespace FileSystemExample
{
class DirectoryExample
{
public static void Main()
{
try
{
string DirectoryName ="TestDirectory";
Console.WriteLine("Adding accesscontrol entry for " + DirectoryName);
// Add the access control entryto the directory.
AddDirectorySecurity(DirectoryName, @"MYDOMAIN\MyAccount",FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Removing access control entry from " +DirectoryName);
// Remove the access controlentry from the directory.
RemoveDirectorySecurity(DirectoryName, @"MYDOMAIN\MyAccount",FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Done.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
// Adds an ACL entry on the specified directory for the specifiedaccount.
public static void AddDirectorySecurity(string FileName, string Account,FileSystemRights Rights, AccessControlType ControlType)
{
// Create a new DirectoryInfo object.
DirectoryInfo dInfo = new DirectoryInfo(FileName);
// Get a DirectorySecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = dInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
dInfo.SetAccessControl(dSecurity);
}
// Removes an ACL entry on the specified directory for the specifiedaccount.
public static void RemoveDirectorySecurity(string FileName, stringAccount, FileSystemRights Rights, AccessControlType ControlType)
{
// Create a new DirectoryInfo object.
DirectoryInfo dInfo = new DirectoryInfo(FileName);
// Get a DirectorySecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = dInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
dInfo.SetAccessControl(dSecurity);
}
}
}
参考资料:
http://msdn.microsoft.com/zh-cn/library/2kzb96fk.aspx
http://msdn.microsoft.com/zh-cn/library/system.security.accesscontrol.filesystemsecurity.aspx
http://msdn.microsoft.com/zh-cn/library/h5e7chcf.aspx