C#常用文件操作总结
在C#中,常用的文件操作包含文件的移动,复制,文件的读写,其中文件的读写分为文本文件以及二进制文件。
文本文件与二进制文件有各自的优缺点,文本文件按照字符的ASCII码进行存储,所以你可以直接用记事本打开文本文件,可以看到文件的内容,但是文件的所有的内容在内存中的表示和在记事本中的表示是不一样的,所以读入内存会存在转码的时间消耗,如果你想让文件直观的话,可以采用文本文件。
二进制文件则是直接存储你需要存储内容的在内存中的直接表示,在读取的时候比较快捷,而且二进制文件的大小要比文本文件小很多。
常用的文件操作类是File,File类是一个静态类,所有的成员函数都为静态函数,所以File类的效率比其他的例如FileInfo类的效率要高。一般情况下,File和FileInfo可以实现的功能大同小异。可以根据自己的需要选择不同的类。
File支持文件的基本操作,包括提供了创建、复制、删除、移动、打开以及获取文件的其他的相关属性的一些方法。
同时,为了更好的支持File文件的操作,C#中定义了一个文件流FileStream,可以将文件加载到文件流FileStream中进行更加方便的操作。
为了对FileStream进行操作,C#定义了两组最常用的操作FileStream的类,一组是StreamReader, StreamWriter, 另外一组是BinaryReader, BinaryWriter,。这两组类分别提供了进行文本文件读写以及二进制文件的读取操作。
文件的操作还有一些其他的类,但是对于常用的一些基本的文件操作,有File, FileStream, StreamReader, StreamWriter,BinaryReader, BinaryWriter,这几个类就足够了。
File类的定义,如下所示:


AppendAllLines(String, IEnumerable<String>)Appends lines to a file, and then closes the file.


AppendAllLines(String, IEnumerable<String>, Encoding)Appends lines to a file by using a specified encoding, and then closes the file.


AppendAllText(String, String)Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.


AppendAllText(String, String, Encoding)Appends the specified string to the file, creating the file if it does not already exist.



AppendTextCreates a StreamWriter that appends UTF-8 encoded text to an existing file.



Copy(String, String)Copies an existing file to a new file. Overwriting a file of the same name is not allowed.



Copy(String, String, Boolean)Copies an existing file to a new file. Overwriting a file of the same name is allowed.



Create(String)Creates or overwrites a file in the specified path.



Create(String, Int32)Creates or overwrites the specified file.


Create(String, Int32, FileOptions)Creates or overwrites the specified file, specifying a buffer size and a FileOptions value that describes how to create or overwrite the file.


Create(String, Int32, FileOptions, FileSecurity)Creates or overwrites the specified file with the specified buffer size, file options, and file security.



CreateTextCreates or opens a file for writing UTF-8 encoded text.


DecryptDecrypts a file that was encrypted by the current account using the Encrypt method.



DeleteDeletes the specified file. An exception is not thrown if the specified file does not exist.


EncryptEncrypts a file so that only the account used to encrypt the file can decrypt it.



ExistsDetermines whether the specified file exists.


GetAccessControl(String)Gets a FileSecurity object that encapsulates the access control list (ACL) entries for a specified file.


GetAccessControl(String, AccessControlSections)Gets a FileSecurity object that encapsulates the specified type of access control list (ACL) entries for a particular file.


GetAttributesGets the FileAttributes of the file on the path.



GetCreationTimeReturns the creation date and time of the specified file or directory.


GetCreationTimeUtcReturns the creation date and time, in coordinated universal time (UTC), of the specified file or directory.



GetLastAccessTimeReturns the date and time the specified file or directory was last accessed.


GetLastAccessTimeUtcReturns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.



GetLastWriteTimeReturns the date and time the specified file or directory was last written to.


GetLastWriteTimeUtcReturns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.



MoveMoves a specified file to a new location, providing the option to specify a new file name.



Open(String, FileMode)Opens a FileStream on the specified path with read/write access.



Open(String, FileMode, FileAccess)Opens a FileStream on the specified path, with the specified mode and access.



Open(String, FileMode, FileAccess, FileShare)Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.



OpenReadOpens an existing file for reading.



OpenTextOpens an existing UTF-8 encoded text file for reading.



OpenWriteOpens an existing file or creates a new file for writing.


ReadAllBytesOpens a binary file, reads the contents of the file into a byte array, and then closes the file.


ReadAllLines(String)Opens a text file, reads all lines of the file, and then closes the file.


ReadAllLines(String, Encoding)Opens a file, reads all lines of the file with the specified encoding, and then closes the file.


ReadAllText(String)Opens a text file, reads all lines of the file, and then closes the file.


ReadAllText(String, Encoding)Opens a file, reads all lines of the file with the specified encoding, and then closes the file.


ReadLines(String)Reads the lines of a file.


ReadLines(String, Encoding)Read the lines of a file that has a specified encoding.


Replace(String, String, String)Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.


Replace(String, String, String, Boolean)Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file and optionally ignores merge errors.


SetAccessControlApplies access control list (ACL) entries described by a FileSecurity object to the specified file.


SetAttributesSets the specified FileAttributes of the file on the specified path.


SetCreationTimeSets the date and time the file was created.


SetCreationTimeUtcSets the date and time, in coordinated universal time (UTC), that the file was created.


SetLastAccessTimeSets the date and time the specified file was last accessed.


SetLastAccessTimeUtcSets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.


SetLastWriteTimeSets the date and time that the specified file was last written to.


SetLastWriteTimeUtcSets the date and time, in coordinated universal time (UTC), that the specified file was last written to.


WriteAllBytesCreates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.


WriteAllLines(String, IEnumerable<String>)Creates a new file, writes a collection of strings to the file, and then closes the file.


WriteAllLines(String,String[])Creates a new file, write the specified string array to the file, and then closes the file.


WriteAllLines(String, IEnumerable<String>, Encoding)Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.


WriteAllLines(String,String[], Encoding) Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.


WriteAllText(String, String)Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.


WriteAllText(String, String, Encoding)Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.Top
然后在看看我们的FileStream类的成员:

FileStream(IntPtr, FileAccess)
Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

FileStream(SafeFileHandle, FileAccess)Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.


FileStream(String, FileMode)Initializes a new instance of the FileStream class with the specified path and creation mode.

FileStream(IntPtr, FileAccess, Boolean)
Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission andFileStream(SafeFileHandle, FileAccess, Int32)Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, and buffer size.


FileStream(String, FileMode, FileAccess)Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.

FileStream(IntPtr, FileAccess, Boolean, Int32)
Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission,FileStream(SafeFileHandle, FileAccess, Int32, Boolean)Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.


FileStream(String, FileMode, FileAccess, FileShare)Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.

FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)
Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission,

FileStream(String, FileMode, FileAccess, FileShare, Int32)Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.


FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state.

FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.Top

BeginReadBegins an asynchronous read. (Overrides Stream.BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).)
In XNA Framework 3.0, this member is inherited from Stream.BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) .


BeginReadBegins an asynchronous read operation. (Inherited from Stream.)


BeginWriteBegins an asynchronous write. (Overrides Stream.BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).)
In XNA Framework 3.0, this member is inherited from Stream.BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) .


BeginWriteBegins an asynchronous write operation. (Inherited from Stream.)


CloseCloses the current stream and releases any resources (such as sockets and file handles) associated with the current stream. (Inherited fromStream.)

CopyTo(Stream)Reads all the bytes from the current stream and writes them to the destination stream. (Inherited fromStream.)

CopyTo(Stream, Int32)Reads all the bytes from the current stream and writes them to a destination stream, using a specified buffer size. (Inherited fromStream.)

CreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited fromMarshalByRefObject.)


CreateWaitHandle
Obsolete. Allocates a WaitHandle object. (Inherited from Stream.)


Dispose()Infrastructure. Releases all resources used by the Stream. (Inherited from Stream.)


Dispose(Boolean)Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. (Overrides Stream.Dispose(Boolean) .)


EndReadWaits for the pending asynchronous read to complete. (Overrides Stream.EndRead(IAsyncResult) .)
In XNA Framework 3.0, this member is inherited from Stream.EndRead(IAsyncResult).


EndReadWaits for the pending asynchronous read to complete. (Inherited from Stream.)


EndWriteEnds an asynchronous write, blocking until the I/O operation has completed. (OverridesStream.EndWrite(IAsyncResult) .)
In XNA Framework 3.0, this member is inherited from Stream.EndWrite(IAsyncResult).


EndWriteEnds an asynchronous write operation. (Inherited from Stream.)


Equals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)


FinalizeEnsures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the

Flush()Clears buffers for this stream and causes any buffered data to be written to the file. (OverridesStream.Flush().)

Flush(Boolean)Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.

GetAccessControlGets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the currentFileStream object.


GetHashCodeServes as a hash function for a particular type. (Inherited from Object.)

GetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited fromMarshalByRefObject.)


GetTypeGets the Type of the current instance. (Inherited from Object.)

InitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited fromMarshalByRefObject.)

LockPrevents other processes from reading from or writing to the FileStream.


MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)

MemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)

ObjectInvariantInfrastructure. Provides support for a Contract. (Inherited from Stream.)


ReadReads a block of bytes from the stream and writes the data in a given buffer. (OverridesStream.Read(Byte[], Int32, Int32).)


ReadByteReads a byte from the file and advances the read position one byte. (OverridesStream.ReadByte().)


SeekSets the current position of this stream to the given value. (Overrides Stream.Seek(Int64, SeekOrigin) .)

SetAccessControlApplies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object.


SetLengthSets the length of this stream to the given value. (Overrides Stream.SetLength(Int64) .)


ToStringReturns a String that represents the current Object. (Inherited from Object.)

UnlockAllows access by other processes to all or part of a file that was previously locked.


WriteWrites a block of bytes to this stream using data from a buffer. (Overrides Stream.Write(Byte[], Int32, Int32).)


WriteByteWrites a byte to the current position in the file stream. (Overrides Stream.WriteByte(Byte) .)Top

CanReadGets a value indicating whether the current stream supports reading. (OverridesStream.CanRead .)


CanSeekGets a value indicating whether the current stream supports seeking. (OverridesStream.CanSeek .)


CanTimeoutGets a value that determines whether the current stream can time out. (Inherited fromStream.)


CanWriteGets a value indicating whether the current stream supports writing. (OverridesStream.CanWrite .)

Handle
Obsolete. Gets the operating system file handle for the file that the current

IsAsyncGets a value indicating whether the

LengthGets the length in bytes of the stream. (Overrides Stream.Length .)


NameGets the name of the

PositionGets or sets the current position of this stream. (Overrides Stream.Position .)


ReadTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. (Inherited fromStream.)

SafeFileHandleGets a SafeFileHandle object that represents the operating system file handle for the file that the currentFileStream object encapsulates.


WriteTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. (Inherited fromStream.)Top
可以看到都是对字节流的操作,这种对于字节流的操作,对于大部分来说还是比较困难的,所以c#又帮助我们封装了对FileStream的操作,那就是StreamReader, StreamWriter, BinaryReader, BinaryWriter.
下面分别看看这两组类怎么使用:
StreamReader, StreamWriter

StreamReader(Stream)Initializes a new instance of the StreamReader class for the specified stream.
StreamReader(String)Initializes a new instance of the StreamReader class for the specified file name.
StreamReader(Stream, Boolean)Initializes a new instance of the StreamReader class for the specified stream, with the specified byte order mark detection option.
StreamReader(Stream, Encoding)Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding.
StreamReader(String, Boolean)Initializes a new instance of the StreamReader class for the specified file name, with the specified byte order mark detection option.
StreamReader(String, Encoding)Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding.
StreamReader(Stream, Encoding, Boolean)Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding and byte order mark detection option.
StreamReader(String, Encoding, Boolean)Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding and byte order mark detection option.
StreamReader(Stream, Encoding, Boolean, Int32)Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.
StreamReader(String, Encoding, Boolean, Int32)Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding, byte order mark detection option, and buffer size.Top
CloseCloses the StreamReader object and the underlying stream, and releases any system resources associated with the reader. (OverridesTextReader.Close().)
CreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited fromMarshalByRefObject.)
DiscardBufferedDataAllows a StreamReader object to discard its current data.
Dispose()Releases all resources used by the TextReader object. (Inherited from TextReader.)
Dispose(Boolean)Closes the underlying stream, releases the unmanaged resources used by the StreamReader, and optionally releases the managed resources. (Overrides TextReader.Dispose(Boolean) .)
Equals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
FinalizeAllows an Object to attempt to free resources and perform other cleanup operations before theObject is reclaimed by garbage collection. (Inherited from Object.)
GetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
GetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited fromMarshalByRefObject.)
GetTypeGets the Type of the current instance. (Inherited from Object.)
InitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited fromMarshalByRefObject.)
MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
MemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
PeekReturns the next available character but does not consume it. (Overrides TextReader.Peek().)
Read()Reads the next character from the input stream and advances the character position by one character. (OverridesTextReader.Read().)
Read(Char[], Int32, Int32) Reads a maximum of
ReadBlockReads a maximum of
ReadLineReads a line of characters from the current stream and returns the data as a string. (OverridesTextReader.ReadLine().)
ReadToEndReads the stream from the current position to the end of the stream. (OverridesTextReader.ReadToEnd().)
ToStringReturns a String that represents the current Object. (Inherited from Object.)Top

BinaryReader(Stream)Initializes a new instance of the BinaryReader class based on the supplied stream and using UTF8Encoding.
BinaryReader(Stream, Encoding)Initializes a new instance of the BinaryReader class based on the supplied stream and a specific character encoding.Top
CloseCloses the current reader and the underlying stream.
Dispose()Releases all resources used by the current instance of the BinaryReader class.
Dispose(Boolean)Releases the unmanaged resources used by the BinaryReader class and optionally releases the managed resources.
Equals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
FillBufferFills the internal buffer with the specified number of bytes read from the stream.
FinalizeAllows an Object to attempt to free resources and perform other cleanup operations before theObject is reclaimed by garbage collection. (Inherited from Object.)
GetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
GetTypeGets the Type of the current instance. (Inherited from Object.)
MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
PeekCharReturns the next available character and does not advance the byte or character position.
Read()Reads characters from the underlying stream and advances the current position of the stream in accordance with the
Read(Byte[], Int32, Int32) Reads the specified number of bytes from the stream, starting from a specified point in the byte array.
Read(Char[], Int32, Int32) Reads the specified number of characters from the stream, starting from a specified point in the character array.
Read7BitEncodedIntReads in a 32-bit integer in compressed format.
ReadBooleanReads a
ReadByteReads the next byte from the current stream and advances the current position of the stream by one byte.
ReadBytesReads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes.
ReadCharReads the next character from the current stream and advances the current position of the stream in accordance with the
ReadCharsReads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the
ReadDecimalReads a decimal value from the current stream and advances the current position of the stream by sixteen bytes.
ReadDoubleReads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes.
ReadInt16Reads a 2-byte signed integer from the current stream and advances the current position of the stream by two bytes.
ReadInt32Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
ReadInt64Reads an 8-byte signed integer from the current stream and advances the current position of the stream by eight bytes.
ReadSByteReads a signed byte from this stream and advances the current position of the stream by one byte.
ReadSingleReads a 4-byte floating point value from the current stream and advances the current position of the stream by four bytes.
ReadStringReads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.
ReadUInt16Reads a 2-byte unsigned integer from the current stream using little-endian encoding and advances the position of the stream by two bytes.
ReadUInt32Reads a 4-byte unsigned integer from the current stream and advances the position of the stream by four bytes.
ReadUInt64Reads an 8-byte unsigned integer from the current stream and advances the position of the stream by eight bytes.
ToStringReturns a String that represents the current Object. (Inherited from Object.)Top