Fork me on GitHub

【Helper】文件IO

一、File方法
   AppendAllText  已重载。 将指定的字符串追加到文件中,如果文件还不存在则创建该文件。 
   AppendText  创建一个 StreamWriter,它将 UTF-8 编码文本追加到现有文件。 
   Copy  已重载。 将现有文件复制到新文件。 
   Create  已重载。 在指定路径中创建文件。 
   CreateText  创建或打开一个文件用于写入 UTF-8 编码的文本。 
   Decrypt  解密由当前帐户使用 Encrypt 方法加密的文件。 
   Delete  删除指定的文件。如果指定的文件不存在,则不引发异常。 
   Encrypt  将某个文件加密,使得只有加密该文件的帐户才能将其解密。
   Equals   已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。) 
   Exists  确定指定的文件是否存在。   
   GetAttributes  获取在此路径上的文件的 FileAttributes。 
   GetCreationTime  返回指定文件或目录的创建日期和时间。  
   GetHashCode   用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。) 
   GetLastAccessTime  返回上次访问指定文件或目录的日期和时间。 
   GetLastAccessTimeUtc  返回上次访问指定的文件或目录的日期及时间,其格式为协调通用时间 (UTC)。 
   GetLastWriteTime  返回上次写入指定文件或目录的日期和时间。 
   GetLastWriteTimeUtc  返回上次写入指定的文件或目录的日期和时间,其格式为协调通用时间 (UTC)。 
   GetType   获取当前实例的 Type。 (从 Object 继承。) 
   Move  将指定文件移到新位置,并提供指定新文件名的选项。 
   Open  已重载。 打开指定路径上的 FileStream。 
   OpenRead  打开现有文件以进行读取。 
   OpenText  打开现有 UTF-8 编码文本文件以进行读取。 
   OpenWrite  打开现有文件以进行写入。 
   ReadAllBytes  打开一个文件,将文件的内容读入一个字符串,然后关闭该文件。 
   ReadAllLines  已重载。 打开一个文本文件,将文件的所有行都读入一个字符串数组,然后关闭该文件。 
   ReadAllText  已重载。 打开一个文本文件,将文件的所有行读入一个字符串,然后关闭该文件。 
   Replace  已重载。 使用其他文件的内容替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份。 
   SetAttributes  设置指定路径上文件的指定的 FileAttributes。 
   ToString   返回表示当前 Object 的 String。 (从 Object 继承。) 
   WriteAllBytes  创建一个新文件,在其中写入指定的字节数组,然后关闭该文件。如果目标文件已存在,则改写该文件。 
   WriteAllLines  已重载。 创建一个新文件,在其中写入指定的字符串,然后关闭文件。如果目标文件已存在,则改写该文件。 
   WriteAllText  已重载。 创建一个新文件,在文件中写入内容,然后关闭文件。如果目标文件已存在,则改写该文件。 

 

二、FileInfo方法

  AppendText  创建一个 StreamWriter,它向 FileInfo 的此实例表示的文件追加文本。 
  CopyTo  已重载。 将现有文件复制到新文件。 
  Create  创建文件。 
  CreateObjRef   创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。 (从 MarshalByRefObject 继承。) 
  CreateText  创建写入新文本文件的 StreamWriter。 
  Decrypt  使用 Encrypt 方法解密由当前帐户加密的文件。 
  Delete  已重写。 永久删除文件。 
  Encrypt  将某个文件加密,使得只有加密该文件的帐户才能将其解密。 
  Equals   已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。) 
  MoveTo  将指定文件移到新位置,并提供指定新文件名的选项。 
  Open  已重载。 用各种读/写访问权限和共享特权打开文件。 
  OpenRead  创建只读 FileStream。 
  OpenText  创建使用 UTF8 编码、从现有文本文件中进行读取的 StreamReader。 
  OpenWrite  创建只写 FileStream。 
  Replace  已重载。 使用当前 FileInfo 对象所描述的文件替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份。   
  ToString  已重写。 以字符串形式返回路径。 

 

三、Directory方法(静态方法)

   CreateDirectory  已重载。 创建指定路径中的所有目录。 
   Delete  已重载。 删除指定的目录。 
   Exists  确定给定路径是否引用磁盘上的现有目录。 
   GetCurrentDirectory  获取应用程序的当前工作目录。 
   GetDirectories  已重载。 获取指定目录中子目录的名称。 
   GetDirectoryRoot  返回指定路径的卷信息、根信息或两者同时返回。 
   GetFiles  已重载。 返回指定目录中的文件的名称。 
   GetFileSystemEntries  已重载。 返回指定目录中所有文件和子目录的名称。 
   GetHashCode   用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。) 
   GetLogicalDrives  检索此计算机上格式为“<驱动器号>:\”的逻辑驱动器的名称。 
   GetParent  检索指定路径的父目录,包括绝对路径和相对路径。  
   Move  将文件或目录及其内容移到新位置。 
   SetCurrentDirectory  将应用程序的当前工作目录设置为指定的目录。 
   ToString   返回表示当前 Object 的 String。 (从 Object 继承。) 

 

四、DirectoryInfo方法

  Create  已重载。 创建目录。 
  CreateSubdirectory  已重载。 在指定路径中创建一个或多个子目录。指定路径可以是相对于 DirectoryInfo 类的此实例的路径。 
  Delete  已重载。 已重写。 从路径中删除 DirectoryInfo 及其内容。 
  Equals   已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。) 
  GetDirectories  已重载。 返回当前目录的子目录。 
  GetFiles  已重载。 返回当前目录的文件列表。 
  GetFileSystemInfos  已重载。 检索表示当前目录的文件和子目录的强类型 FileSystemInfo 对象的数组。 
  GetHashCode   用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。) 
  GetLifetimeService   检索控制此实例的生存期策略的当前生存期服务对象。 (从 MarshalByRefObject 继承。) 
  GetObjectData   设置带有文件名和附加异常信息的 SerializationInfo 对象。 (从 FileSystemInfo 继承。) 
  GetType   获取当前实例的 Type。 (从 Object 继承。) 
  MoveTo  将 DirectoryInfo 实例及其内容移动到新路径。     
  ToString  已重写。 返回用户所传递的原始路径。 

 

五、FileAttributes枚举

 ReadOnly 文件为只读。
 Hidden 文件是隐藏的,因此没有包括在普通的目录列表中。
 System 文件为系统文件。文件是操作系统的一部分或由操作系统以独占方式使用。
 Directory 文件为一个目录。
 Archive 文件的存档状态。应用程序使用此属性为文件加上备份或移除标记。
 Device 保留供将来使用。
 Normal 文件正常,没有设置其他的属性。此属性仅在单独使用时有效。
 Temporary 文件是临时文件。文件系统试图将所有数据保留在内存中以便更快地访问,而不是将数据刷新回大容量存储器中。不再需要临时文件时,应用程序会立即将其删除。
 SparseFile 文件为稀疏文件。稀疏文件一般是数据通常为零的大文件。
 ReparsePoint 文件包含一个重新分析点,它是一个与文件或目录关联的用户定义的数据块。
 Compressed 文件已压缩。
 Offline 文件已脱机。文件数据不能立即供使用。
 NotContentIndexed 操作系统的内容索引服务不会创建此文件的索引。
 Encrypted 该文件或目录是加密的。对于文件来说,表示文件中的所有数据都是加密的。对于目录来说,表示新创建的文件和目录在默认情况下是加密的。

 

六、Path方法(静态方法)

   ChangeExtension  更改路径字符串的扩展名。 
   Combine  合并两个路径字符串。 
   Equals   已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。) 
   GetDirectoryName  返回指定路径字符串的目录信息。 
   GetExtension  返回指定的路径字符串的扩展名。 
   GetFileName  返回指定路径字符串的文件名和扩展名。 
   GetFileNameWithoutExtension  返回不具有扩展名的指定路径字符串的文件名。 
   GetFullPath  返回指定路径字符串的绝对路径。 
   GetInvalidFileNameChars  获取包含不允许在文件名中使用的字符的数组。 
   GetInvalidPathChars  获取包含不允许在路径名中使用的字符的数组。 
   GetPathRoot  获取指定路径的根目录信息。 
   GetRandomFileName  返回随机文件夹名或文件名。 
   GetTempFileName  创建磁盘上唯一命名的零字节的临时文件并返回该文件的完整路径。 
   GetTempPath  返回当前系统的临时文件夹的路径。  
   HasExtension  确定路径是否包括文件扩展名。 
   IsPathRooted  获取一个值,该值指示指定的路径字符串是包含绝对路径信息还是包含相对路径信息。 

 

七、StreamWriter方法

 Close 关闭当前的 StreamWriter 对象和基础流。 (重写 TextWriter..::.Close()()()。) 
 Dispose 已重载。  
 Finalize 已重载。 
 Flush 清理当前编写器的所有缓冲区,并使所有缓冲数据写入基础流。 (重写 TextWriter..::.Flush()()()。) 
 Write 已重载。 写入流。
 WriteLine 已重载。 

 

八、FileStream方法

 BeginRead 已重载。 
 BeginWrite 已重载。 
 Close 已重载。 
 Dispose 已重载。 
 EndRead 已重载。 
 EndWrite 已重载。 
 Finalize 确保垃圾回收器回收 FileStream 时释放资源并执行其他清理操作。 (重写 Object..::.Finalize()()()。)
 Flush 清除该流的所有缓冲区会使得所有缓冲的数据都将写入到文件系统。 (重写 Stream..::.Flush()()()。)
 GetAccessControl 获取 FileSecurity 对象,该对象封装当前 FileStream 对象所描述的文件的访问控制列表 (ACL) 项。
 Lock 允许读取访问的同时防止其他进程更改 FileStream。
 Read 从流中读取字节块并将该数据写入给定缓冲区中。 (重写 Stream..::.Read(array<Byte>[]()[], Int32, Int32)。)
 ReadByte 从文件中读取一个字节,并将读取位置提升一个字节。 (重写 Stream..::.ReadByte()()()。)
 Seek 将该流的当前位置设置为给定值。 (重写 Stream..::.Seek(Int64, SeekOrigin)。)
 SetLength 将该流的长度设置为给定值。 (重写 Stream..::.SetLength(Int64)。)
 ToString 返回表示当前 Object 的 String。 (继承自 Object。)
 Unlock 允许其他进程访问以前锁定的某个文件的全部或部分。
 Write 使用从缓冲区读取的数据将字节块写入该流。 (重写 Stream..::.Write(array<Byte>[]()[], Int32, Int32)。)
 WriteByte 将一个字节写入文件流的当前位置。 (重写 Stream..::.WriteByte(Byte)。)

 

九、DriveInfo&DriveType

    GetDrives  检索计算机上的所有逻辑驱动器的驱动器名称。 
    GetHashCode   用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。)  
    ToString  已重写。 将驱动器名称作为字符串返回。 
 CDRom 此驱动器是一个光盘设备,如 CD 或 DVD-ROM。 
 Fixed 此驱动器是一个固定磁盘。 
 Network 此驱动器是一个网络驱动器。 
 NoRootDirectory 此驱动器没有根目录。 
 Ram 此驱动器是一个 RAM 磁盘。 
 Removable 此驱动器是一个可移动存储设备,如软盘驱动器或 USB 闪存驱动器。 
 Unknown 驱动器类型未知。 

 

IO操作最后介绍两个压缩算法:

DeflateStream

using System;
using System.IO;
using System.IO.Compression;

public class DeflateTest
{
    public static int ReadAllBytesFromStream(Stream stream, byte[] buffer) 
    {
    // Use this method is used to read all bytes from a stream.
    int offset = 0;
    int totalCount = 0;
        while (true) 
        {
        int bytesRead = stream.Read(buffer, offset, 100); 
            if ( bytesRead == 0) 
            {
            break; 
            }
    offset += bytesRead;
    totalCount += bytesRead; 
        }
    return totalCount;
    } 

    public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2) 
    {
        // Use this method to compare data from two different buffers.
        if (len1 != len2) 
        { 
        Console.WriteLine("Number of bytes in two buffer are different {0}:{1}", len1, len2);
        return false;
        }

        for ( int i= 0; i< len1; i++) 
        {
            if ( buf1[i] != buf2[i]) 
            {
            Console.WriteLine("byte {0} is different {1}|{2}", i, buf1[i], buf2[i]);
            return false;
            }
        }
    Console.WriteLine("All bytes compare.");
    return true; 
    }

    public static void DeflateCompressDecompress(string filename)
    {
    Console.WriteLine("Test compression and decompression on file {0}", filename);
    FileStream infile;
        try
        {
        // Open the file as a FileStream object.
        infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
        byte[] buffer = new byte[infile.Length];
        // Read the file to ensure it is readable.
        int count = infile.Read(buffer, 0, buffer.Length);
            if ( count != buffer.Length) 
            {
            infile.Close();
            Console.WriteLine("Test Failed: Unable to read data from file"); 
            return;
            }
        infile.Close();
        MemoryStream ms = new MemoryStream();
        // Use the newly created memory stream for the compressed data.
        DeflateStream compressedzipStream = new DeflateStream(ms , CompressionMode.Compress, true);
        Console.WriteLine("Compression");
        compressedzipStream.Write(buffer, 0, buffer.Length);
        // Close the stream.
        compressedzipStream.Close();
        Console.WriteLine("Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);

        // Reset the memory stream position to begin decompression.
        ms.Position = 0;
        DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress);
        Console.WriteLine("Decompression");
        byte[] decompressedBuffer = new byte[buffer.Length + 100];
        // Use the ReadAllBytesFromStream to read the stream.
        int totalCount = DeflateTest.ReadAllBytesFromStream(zipStream, decompressedBuffer);
        Console.WriteLine("Decompressed {0} bytes", totalCount);

        if( !DeflateTest.CompareData(buffer, buffer.Length, decompressedBuffer, totalCount) ) 
        {
        Console.WriteLine("Error. The two buffers did not compare.");
        }
    zipStream.Close(); 
        } // end try
        catch (InvalidDataException)
        {
            Console.WriteLine("Error: The file being read contains invalid data.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error:The file specified was not found.");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("Error: path is a zero-length string, contains only white space, or contains one or more invalid characters");
        }
        catch (PathTooLongException)
        {
            Console.WriteLine("Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine("Error: The specified path is invalid, such as being on an unmapped drive.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: An I/O error occurred while opening the file.");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.");
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Error: You must provide parameters for MyGZIP.");
        }
    }
    public static void Main(string[] args)
    {
        string usageText = "Usage: DeflateTest <inputfilename>";
        //If no file name is specified, write usage text.
        if (args.Length == 0)
        {
            Console.WriteLine(usageText);
        }
        else
        {
            if (File.Exists(args[0]))
                DeflateCompressDecompress(args[0]);
        }
    }
}
    

GZipStream
using System;
using System.IO;
using System.IO.Compression;

public class GZipTest
{
    private const int buffer_size = 100;

    public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
    {
        // Use this method is used to read all bytes from a stream.
        int offset = 0;
        int totalCount = 0;
        while (true)
        {
            int bytesRead = stream.Read(buffer, offset, buffer_size);
            if (bytesRead == 0)
            {
                break;
            }
            offset += bytesRead;
            totalCount += bytesRead;
        }
        return totalCount;
    }

    public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2)
    {
        // Use this method to compare data from two different buffers.
        if (len1 != len2)
        {
            Console.WriteLine("Number of bytes in two buffer are different {0}:{1}", len1, len2);
            return false;
        }

        for (int i = 0; i < len1; i++)
        {
            if (buf1[i] != buf2[i])
            {
                Console.WriteLine("byte {0} is different {1}|{2}", i, buf1[i], buf2[i]);
                return false;
            }
        }
        Console.WriteLine("All bytes compare.");
        return true;
    }

    public static void GZipCompressDecompress(string filename)
    {
        Console.WriteLine("Test compression and decompression on file {0}", filename);
        FileStream infile;
        try
        {
            // Open the file as a FileStream object.
            infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] buffer = new byte[infile.Length];
            // Read the file to ensure it is readable.
            int count = infile.Read(buffer, 0, buffer.Length);
            if (count != buffer.Length)
            {
                infile.Close();
                Console.WriteLine("Test Failed: Unable to read data from file");
                return;
            }
            infile.Close();
            MemoryStream ms = new MemoryStream();
            // Use the newly created memory stream for the compressed data.
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
            Console.WriteLine("Compression");
            compressedzipStream.Write(buffer, 0, buffer.Length);
            // Close the stream.
            compressedzipStream.Close();
            Console.WriteLine("Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);

            // Reset the memory stream position to begin decompression.
            ms.Position = 0;
            GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress);
            Console.WriteLine("Decompression");
            byte[] decompressedBuffer = new byte[buffer.Length + buffer_size];
            // Use the ReadAllBytesFromStream to read the stream.
            int totalCount = GZipTest.ReadAllBytesFromStream(zipStream, decompressedBuffer);
            Console.WriteLine("Decompressed {0} bytes", totalCount);

            if (!GZipTest.CompareData(buffer, buffer.Length, decompressedBuffer, totalCount))
            {
                Console.WriteLine("Error. The two buffers did not compare.");
            }
            zipStream.Close();
        } // end try
        catch (InvalidDataException)
        {
            Console.WriteLine("Error: The file being read contains invalid data.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error:The file specified was not found.");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("Error: path is a zero-length string, contains only white space, or contains one or more invalid characters");
        }
        catch (PathTooLongException)
        {
            Console.WriteLine("Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine("Error: The specified path is invalid, such as being on an unmapped drive.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: An I/O error occurred while opening the file.");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.");
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Error: You must provide parameters for MyGZIP.");
        }
    }

    public static void Main(string[] args)
    {
        string usageText = "Usage: MYGZIP <inputfilename>";
        //If no file name is specified, write usage text.
        if (args.Length == 0)
        {
            Console.WriteLine(usageText);
        }
        else
        {
            if (File.Exists(args[0]))
                GZipCompressDecompress(args[0]);
        }
    }
}
   
posted @ 2010-01-06 22:14  idoku  阅读(391)  评论(0编辑  收藏  举报