c#学习笔记(操作文件和注册表)

System.IO命名空间下包含了文件输入输出相关的类
BinaryReader/BingarWriter:二进制形式读写
BufferedStream:给另一流上的读写添加缓冲层,无法继承此类
Directory/DirectoryInfo/DirectoryNotFoundException:提供目录操作的静态/实例方法
DriveInfo/DriveNotFoundException:提供驱动器信息
EndOfStreamException:读操作试图超出流的末尾
ErrorEventArgs:
File/FileInfo/FileNotFoundException:提供文件操作的静态/实例方法
FileLoadException:当找到托管程序集却不能加载它时引发的异常
FileStream:以文件为主的Stream,支持同步或异步读写操作。通过Lock和Unlock方法实现单通道操作。
FileSystemEventArgs:提供目录事件Changed、Created、Deleted的数据
FileSystemInfo:为FileInfo和DirectoryInfo对象提供基类
FileSystemWatcher:侦听文件系统更改通知
InternalBufferOverflowException:内部缓冲区溢出时引发的异常
InvalidDataException:数据流格式无效时的异常
IODescriptionAttribute:设置可视化设计器在引用事件、扩展程序或属性时可显示的说明
IOException:发生I/O错误
MemoryStream:创建支持存储区为内存的流
Path/pathTooLongException:对文件或目录的路径信息操作
RenamedEventArgs
Stream:提供字节序列的一般视图
StreamReader/StreamWriter:实现一个TextReader/TextWriter,从字节流读写
StringReader/StringWriter:TextReader/TextWriter,从字符串读写
TextReader/TextWriter:连续有序字符系列的读写器
UnmanagedMemoryStream:提供从托管代码访问非托管代码内存块的能力

 

ContractedBlock.gif ExpandedBlockStart.gif FileStream类读写文件
//使用FileStream类读写文件
    class RWFile
ExpandedBlockStart.gifContractedBlock.gif    
{
        
public void WriteFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
byte [] m_bDataWrite=new  byte[100];
            
char[] m_cDataWrite = new char[100];
            
//创建d:\file.txt的FileStream对象
            FileStream m_FilesStream = new FileStream(@"d:\file.txt", FileMode.OpenOrCreate);
            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{   
                
//将要写入的字符串转换成字符数组
                m_cDataWrite = "My First File Operation".ToCharArray();
                Encoder m_Enc 
= Encoding.UTF8.GetEncoder();

                
//通过UTF-8编码将字符数组转换成字节数组
                m_Enc.GetBytes(m_cDataWrite, 0, m_cDataWrite.Length, m_bDataWrite, 0true);
                
//设置流的当前位置为文件开始位置
                m_FilesStream.Seek(0, SeekOrigin.Begin);
                
//将字节数组中的内容写入文件
                m_FilesStream.Write(m_bDataWrite, 0, m_bDataWrite.Length);
               
            }

            
catch (IOException e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Console.WriteLine(e.Message);
                
return;
            }

            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                m_FilesStream.Close();
            }

        }


        
public void ReadFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
byte[] m_bDataRead = new byte[100];
            
char[] m_cDataRead = new char[100];
            
//创建d:\file.txt的FileStream对象
            FileStream m_FilesStream = new FileStream(@"d:\file.txt", FileMode.Open);
            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//设置流的当前位置为文件开始位置
                m_FilesStream.Seek(0, SeekOrigin.Begin);
                
//将文件内容读入到字节数组中
                m_FilesStream.Read(m_bDataRead, 0, m_bDataRead.Length);

            }

            
catch (IOException e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Console.WriteLine(e.Message);
                
return;
            }

            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{ 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);
        }

    }

 

StreamWrite/StreamReader类读写文件比FileStream更为方便,无需额外的数据类型转换操作 

ContractedBlock.gif ExpandedBlockStart.gif StreamWriter/StreamReader读写文件
 //使用StreamWriter/StreamReader类读写文件
    class RWFile
ExpandedBlockStart.gifContractedBlock.gif    
{
        
public void WriteFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//追加写入方式打开文件
            StreamWriter m_SW = new StreamWriter(@"d:\file.txt",true);
            
            
//将要写入的字符串转换成字符数组
            m_SW.WriteLine("StreamWriter write this file");           
            m_SW.Close();
         }


        
public void ReadFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            StreamReader m_SW 
= new StreamReader(@"d:\file.txt");
            
string m_Data = m_SW.ReadToEnd();
            Console.WriteLine(m_Data);
            m_SW.Close();
        }

    }

 

BinaryWriter/BinaryReader以二进制将基元类型写入流,并支持用特定的编码写入字符串。输出文件需用查看16进制的阅读器才能正确阅读 

ContractedBlock.gif ExpandedBlockStart.gif BinaryWriter/BinaryReader类读写文件
//使用BinaryWriter/BinaryReader类读写文件
    class RWFile
ExpandedBlockStart.gifContractedBlock.gif    
{
        
public void WriteFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//追加写入方式打开文件
           FileStream m_FS = new FileStream(@"d:\file.txt",FileMode.Append);
           BinaryWriter m_BW 
= new BinaryWriter(m_FS);
           
for (int i = 0; i < 11; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{ m_BW.Write(i);}

           m_BW.Close();         
           m_FS.Close();
         }


        
public void ReadFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            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++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{ Console.WriteLine(m_BR.ReadInt32());}
            m_BR.Close();
            m_FS.Close();
        }

    }

 

FileSystemWatcher可用于监视文件的操作

 

ContractedBlock.gif ExpandedBlockStart.gif FileSystemWatcher监视文件变化
class Program
ExpandedBlockStart.gifContractedBlock.gif    
{
        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            WatcheFile watchFile 
= new WatcheFile();
            
while (true)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                watchFile.WatchFile();
                
//有个问题,事件会被多次触发,待解决??
                System.Threading.Thread.Sleep(10000);
            }

        }

    }

    
//使用FileSystemWatcher类监视文件改变
    class WatcheFile
ExpandedBlockStart.gifContractedBlock.gif    
{
        
public void WatchFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            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;
        }

        
void watcher_Changed(object sender,FileSystemEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Console.WriteLine(e.Name 
+"改变了");
        }

        
void watcher_Created(object sender, FileSystemEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Console.WriteLine(e.Name 
+ "创建了");
        }

        
void watcher_Deleted(object sender, FileSystemEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Console.WriteLine(e.Name 
+ "删除了");
        }

        
void watcher_Renamed(object sender, FileSystemEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Console.WriteLine(e.Name 
+ "改名了");
        }

    }

 

异步IO:
应用异步IO适用于对大型文件的读写操作,它的步骤是:
a.自定义一个无返回值的方法,此方法须接受一个IAsyncResult类型的接口做参数
b.声明一个AsynCallBack代理类型,以上面自定义的方法名称为参数
c.引用方法BeginRead读取文件或BeginWrite写操作
d.在自定义方法中使用方法EndRead取得BeginRead所读取的字节数组
e.BeginRead和BeginWrite的第四参数指定异步IO完成时调用的方法,最后一个参数为状态对象,设为null即可

ExpandedBlockStart.gif 异步写操作
class  AsynchronousIO
    {
        FileStream myFileStream;
        
double  lngNumber  =   100000000 ;

        
static   void  Main( string [] args)
        {
            AsynchronousIO myAsynchronousIO 
=   new  AsynchronousIO();
            myAsynchronousIO.longProcessWrite();
            Console.Read();
        }

        
public   void  longProcessWrite()
        {
            
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   void  WriteEnd(IAsyncResult asyncResult)
        {
            Console.WriteLine(
" 文件写入完毕! " );
        }
    }

 

 隔离存储:
允许根据不同用户、组件或安全级别存放数据

 

ExpandedBlockStart.gif 隔离存储
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  =   new  IsolatedStorageFileStream
                (
" 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  in  myIsoStore.GetFileNames( " *.bin " ))
            {
                Console.WriteLine(filename);
            }
            Console.WriteLine(
" ==================== " );
            Console.WriteLine(
" 列出根目录下所有文件! " );
            
foreach  ( string   filename  in  myIsoStore.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  in  myIsoStore.GetFileNames(directory  + " / " + sdirectory + " /* " ))
                    {
                        Console.WriteLine(
" \t " + filename);
                    }
                }
            }
            myIsoStore.DeleteFile(
" isFile1.bin " );
            myIsoStore.DeleteDirectory(
" ISDRoot2 " );
            myIsoStore.Close ();            
            Console.Read();
        }
    }

 

 

 

 

 

posted on 2009-11-26 14:16 eaglegrace 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/eaglespace/archive/2009/11/26/1611323.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值