C # files and streams (FileStream, StreamWriter, StreamReader, file, FileInfo, Directory, DirectoryInfo, Path, Encoding)

Source: Internet
Author: User
Tags binary to decimal

(FileStream, StreamWriter, StreamReader, File, FileInfo, Directory, DirectoryInfo, Path, Encoding)

C # files and streams (FileStream, StreamWriter, StreamReader, file, FileInfo, Di, you can refer to the required friends.

Files and Streams (FileStream, StreamWriter, StreamReader, file, FileInfo, Directory, DirectoryInfo, Path, Encoding)
10.1, FileStream 10.1.1, define a Stream object

Stream FS =new FileStream (@ "D:\FINISH. TXT ", filemode.open,fileaccess.read,fileshare.read);

Description

Stream is the parent class, FileStream is a subclass, the parent class is an abstract class, and the subclass is the implementation class.

FileMode is an enumeration type that has many values:

Open: Indicates that the stream object should open an existing file, and if the file does not exist, the exception will be opened.

CreateNew: Indicates that a new file is created and an exception occurs if the file exists.

Create: Indicates that a new file is created, and if the file exists, it will be overwritten (emptied and then written).

OpenOrCreate: Indicates that the file is open if it exists and is created if it does not exist.

FileAccess: Control the access of this stream to the file: read, write and read/write.

FileShare: When the current stream accesses the specified file, it controls the access of the other stream to the file: read, write, read and write, without any permissions, by default, the outside world is not authorized to access the file unless specified.

10.1.2, reading files

Stream FS =new FileStream (@ "D:\FINISH. TXT ", FileMode.Open);

int length = fs. Read (byte[] buffer,intoffset,intcount);

Buffer: This is a byte array, which is used to store the read files.

Offset: This is the offset in buffer relative to the starting index 0, which is stored from offset.

Count: The number of bytes that are scheduled to be read from the stream file, count does not go beyond the length of buffer.

Return value: The function returns the number of bytes actually read from the file. 0<= return value <= count

Attention:

For the read function, as long as the stream does not close the file it points to, the first read begins with the first byte, the second reads from the next beginning of the last byte of the first read, and the seek automatically moves the position of the file that the stream is pointing to later, and so on.

When reading a file, FS has a length property that represents the byte size of the file it points to, that is, the total length of the file.

10.1.3, writing files

Stream FS =new FileStream (@ "D:\FINISH. TXT ", FileMode. Create);

Fs. Write (byte[] buffer,intoffset,intcount);

Buffer: This is a byte array, that is, the data in the byte array is written to the file.

Offset: This is the offset in buffer relative to the starting index 0, which is the read buffer starting with offset.

Count: Number of bytes read from buffer, written to the file, Count <=buffer.length-offset.

Return value: The function has no return value.

Note: For the Write function, if the file is already present, the file is emptied before the first write, and then as long as the stream does not close the file it points to, the first write is written from the beginning of the file, and the second write is from the next beginning of the last byte of the first write. There is a seek that automatically moves the position of the file currently pointed to by the stream, followed by a subsequent write.

This write is written only to the buffer, not yet in the file, and to actually write to the file, you must also rely on the following function:

Fs. Flush ();

This is to write the contents of the buffer into the underlying stream and empty the buffer so that the contents can be found in the file. As long as the file is not closed, you can keep writing and flush, followed by the write to the end of the file. If the buffer is large, you can write a portion and flush the part, multiple write and flush.

10.1.4, closing files

Fs. Close ()

This writes the contents of the buffer to the underlying stream and empties the buffer so that, even without flush (), the flush () function is done as it is called, and the connection between the stream and the file it points to is closed and all resources associated with it are released. This file has no relationship with the stream and can continue to be accessed by other streams. So be sure to close the stream when it's finished. When the stream is closed, it is no longer possible to manipulate the file with the previous stream object, or it will go wrong.

10.2. Conversion of bytes to integers, floating-point numbers, and strings

When reading and writing files, it is often involved in the conversion of values and bytes, the conversion of strings to bytes, respectively, the following are explained:

10.2.1, 32-bit integers and byte conversions

byte[] buffer =bitconverter.getbytes (int a);

This is a 32-bit integer (what we see is a decimal integer, 32 bits refers to a binary deposit in the computer, occupies 32 bit bits) converted into a byte array of length 4:32-bit integer represents the binary 32 bit bit, exactly corresponds to 4 bytes, in bytes, From the low eight-bit to the high eight-bit plus is exactly 32-bit, the lowest bit is two 0 times, and then two of the square, and so on, and so on, so when the conversion, the first decimal 32-bit integer is converted into 32 bits according to the binary, and then divided into eight bytes, respectively, stored in buffer, The low eight bits of an integer are stored in buffer[0], the highest eight bits are stored in buffer[3], and the number of each byte that is seen when compiling debugging is the value of a single byte converted from binary to decimal.

int a =bitconverter.toint32 (byte[] buffer,intstartindex)

This is the four bytes in buffer, starting with StartIndex, converted to 32-bit integer values from low eight to high eight bits, StartIndex is low eight bits, StartIndex + 3 is eight bits high.

10.2.2, 64-bit double and byte conversion

byte[] Buffer =bitconverter.getbytes (double a);

This is to convert a 64-bit double into a byte array of length 8, where the low eight bits of the double are stored in buffer[0], and the highest eight bits are stored in buffer[7].

Double A =bitconverter. ToDouble (byte[] buffer,int startIndex)

This is the eight bytes in buffer, starting with startindex, converted to a 64-bit double value in the order from low eight bits to eight bits high.

10.2.3, string-to-byte conversions

byte[] Buffer =encoding.default.getbytes (Stringa);

This is to convert a string into a byte array.

Strings =encoding.default.getstring (byte[] buffer,intstartindex,intcount);

This is the conversion of the buffer array into a string, startindex is the starting index in buffer, and count is the length of bytes to be converted in buffer.

10.3, StreamWriter, StreamReader

When reading and writing files, often to read and write text files, when reading and writing text files, there are two classes are very convenient.

10.3.1, writing text files

StreamWriter SW =new StreamWriter (@ "D:\test.txt");

Once a StreamWriter object is defined, the file is created without a file, and the contents of the file are emptied (this is the constructor in this section, but other overloaded constructors can be called to accomplish different functions).

Sw. WriteLine ("123");

This function writes a string to the end of the file, and automatically adds a \ r \ n line break.

Sw. Write ("123");

This writes a string to the end of the file and does not add \ r \ n line break.

Note: The above two functions are only written to the buffer, but at this point to view the file, the file is still not written.

Sw. Flush ();

This is to write the contents of the buffer into the underlying stream and empty the buffer so that the contents can be found in the file. As long as the file is not closed, you can keep writing and flush, followed by the write to the end of the file. If the buffer is large, you can write a portion and flush the part, multiple write and flush.

Sw. Close ()

This writes the contents of the buffer to the underlying stream and empties the buffer so that, even without flush (), the flush () function is done as it is called, and the connection between the stream and the file it points to is closed and all resources associated with it are released. This file has no relationship with the stream and can continue to be accessed by other streams. So be sure to close the stream when it's finished. When the stream is closed, it is no longer possible to manipulate the file with the previous stream object, or it will go wrong.

10.3.2, read text file

StreamReader SR =new StreamReader (@ "D:\test.txt", Encoding.default);

String str = Sr. ReadLine ();

This function reads a line from a text file and deletes the following \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ n Reads are always read from the last read, and if all rows are read, the read again returns NULL.

String str = Sr. ReadToEnd ();

Reads the entire text file, returned as a string.

Note: To close the stream after the last operation is complete. If the file does not exist, it will be abnormal at the time of definition.

10.4. File

The class is a file-related class, a static class, and the function inside it is a static function. A static method for creating, deleting, moving, and opening files is provided primarily.

10.4.1, File copy

File.Copy (String sourcefilename,string destfilename)

Two parameters contain the full path and file name, the destination path cannot have a file with the same name as destFileName, otherwise it will be abnormal.

File.Copy (string sourcefilename,string destfilename,bool overwrite)

The first two parameters contain the full path and file name, and the last parameter indicates whether the file is overwritten if there is a file with the same name in the destination path.

10.4.2, determine whether the file exists

File.exists (string path);

BOOL Isexist =file.exists (@ "C:\ZWJ");

Returns true if the file specified by path still exists, otherwise false

10.4.3, deleting files

File.delete (string path);

Deletes the file specified by path. If it exists, it is deleted, does not exist, and does not throw an exception.

10.4.4, File movement

File.move (String sourcefilename,string destfilename)

Two parameters contain the full path and file name, the destination path cannot have a file with the same name as destFileName, otherwise it will be abnormal.

10.4.5, creating files

File.create (string path);

If the file does not exist, it is created, if it exists and is writable, then an exception occurs if there is no write.

By default, newly created files are readable and writable.

10.4.6, file-related hours

File.getcreationtime (string path);

This function is to get the creation time of the file and return the DateTime.

File.getlastaccesstime (string path);

This function is to get the last time the file was accessed, returning a DateTime.

File.getlastwritetime (string path);

This function is to get the last modification time of the file, returning the DateTime.

10.5, FileInfo class

The class is also a file-related class, but the class is not a static class, and the class must be instantiated before it can be used.

FileInfo fi =new FileInfo (string fileName);

10.5.1, copying

Fi. CopyTo (String destfilename)

The destination path cannot have a file with the same name as destFileName, otherwise it will be abnormal.

Fi. CopyTo (String Destfilename,bool overwrite)

The last parameter indicates whether the file is overwritten if there is a file with the same name in the destination path.

Note: The above two functions will return the FileInfo object, which is pointing to destFileName.

10.5.2, deleting

Fi. Delete ();

Permanently delete the file, the file does not exist and the exception does not occur.

10.5.3, Mobile

Fi. MoveTo (String destfilename)

The destination path cannot have a file with the same name as destFileName, otherwise it will be abnormal.

10.5.4, properties

D:\programmfile\zwj.txt

1, CreationTime: Gets or sets the creation time of the file. Returns a DateTime.

2, LastWriteTime: The last modification time. Returns a DateTime.

3, Lastacesstime: Last access time. Returns a DateTime.

4. DirectoryName: Gets the string that contains the full path of the directory containing the file: D:\programmfile

5. FullName: Gets the full path including the file name: D:\programmfile\zwj.txt

6. Name: Get the file name and extension: Zwj.txt

7. Extension: Gets the file extension:. txt

8, Exists: Indicates whether the file exists, there is a return true, otherwise false.

9, IsReadOnly: Gets or sets whether the current file is read-only. Yes returns true, otherwise false.

10. Length: Returns the length of the file, in bytes. Long integer type.

11. Directory: Gets the DirectoryInfo instance of the directory that contains the file.

10.6. Summary of documents

1, whether to create a file or read a file, as long as the path of the file is only a filename, and there is no absolute path, then the file name is implicitly considered under the current directory. This is currently possible in the change, the program began to start, the current must be EXE the same level directory below, but sometimes after the program started, then some operations, such as export to the Excle report, select the other folder path, then the current path is the new path instead of the same level of EXE directory.

2 、.. \: This represents the top-level directory of the current directory. This current directory is as likely to change as above.

3, when a file for the first time to write operations, the first will be the contents of the file empty.

4. If you want to find the path of a fixed EXE file:

Application.executablepath: Gets the path to the startup application executable file, including the name of the executable file:

E: \source\ Stored procedure version \pvpt\mainmenu\bin\debug\mainmenu.exe

Application.startuppath: Gets the path to the startup application executable file, not including the name of the executable file:

E: \source\ Stored procedure version \pvpt\mainmenu\bin\debug (not \)

10.7. Directory

The class is a directory-related class and is a static class that contains both static and static properties.

1. Create a Directory

Directory.CreateDirectory (string path);

Creates a directory, subdirectory, and a DirectoryInfo object that points to path, as specified by path. This is the creation of a directory, not a file, a logical disk cannot be created by "R:", only the directory can be created under an existing logical disk. Duplicate creation of a directory that already exists is not an exception. Any newly created directory name cannot have the same name as the one in the directory at the same level, or an error will be made.

2. Delete Directory

Directory.delete (string path);

This function is to delete the directory, this directory must be an empty directory, that is, there is no directory and files. otherwise exception. The directory does not exist and will be abnormal.

Directory.delete (string path,bool recursive);

This function is to delete the directory, when recursive is true, then you can delete the empty directory unless the empty directory. The directory does not exist and will be abnormal.

3. Mobile Directory

Voiddirectory.move (String sourcedirname,string destdirname)

Move the contents of the original directory to the target directory and delete the original directory.

4. Determine if the directory exists

Directory.Exists (string path);

The presence returns TRUE, otherwise false is returned.

5, get the creation time of the directory: DateTime directory.getcreationtime (string path);

6, get the last access time of the directory: DateTime directory.getlastaccesstime (String path)

7, get the last modification time of the directory: DateTime directory.getlastwritetime (String path)

8. Get the directory where the current execution program is located: String directory.getcurrentdirectory (string path);

9, string[] directory.getdirectories (string path);

Gets the subdirectory name in the specified directory, but only the next level of the specified directory, not the next level two or lower three. Returns a complete array of path strings, including the directory name.

10, string[] Directory.GetFiles (string path);

Gets the name of the sub-file in the specified directory, but only the next level of the specified directory, not the next level two or lower three. Returns a complete array of path strings, including the file name.

11, String Directory.getdirectoryroot (string path)

Gets the root directory, volume information, such as "D:\", of the path executed by path, which can be a file or directory

12, string[] directory.getlogicaldrives ();

Get the logical disk of the system and return it as a string. such as: "D:\"

13, DirectoryInfo directory.getparent (string path);

14. Gets the parent directory of the specified path, returns the DirectoryInfo object, and path can be a file and directory. If path is the root directory, then NULL is returned.

Note: Do not add "\" to the directory at the end

10.8, DirectoryInfo class

The class is also a catalog-related class, but the class is not a static class, and the class must be instantiated before it can be used.

DirectoryInfo di =new DirectoryInfo (@ "D:\Program Files");

10.8.1, properties

1, CreationTime: Gets or sets the creation time of the directory. Returns a DateTime.

2, LastWriteTime: The last modification time. Returns a DateTime.

3, Lastacesstime: Last access time. Returns a DateTime.

4, Exists: Indicates whether the directory exists, there is a return true, otherwise false.

5. FullName: Gets the full path of the directory and returns a string.

6. Extension: Gets the name extension of the directory and returns a string.

7. Name: Does not include the directory name of the path, that is, the name of the folder, return string.

8, Parent: Gets the parent directory, returns null if the current directory is the root directory, or returns DIRECTORYINFO.

9. Root: Gets the root directory of the current directory and returns DirectoryInfo.

10.8.2, methods

1, DirectoryInfo di. Createsubdirectory (String path)

This creates subdirectories, double directories, and returns a new DirectoryInfo object under the current directory. For example, Path:a\b\c,a cannot have a \ in front.

2, void Di. Delete ()

This represents the deletion of the empty directory specified by Di and throws an exception if there is content in the directory.

void Di. Delete (BOOL)

If the directory is not empty, then true means delete all, false indicates not to delete. If the directory is empty, either true or false will be deleted directly.

3, DirectoryInfo [] di. GetDirectories ();

Returns all subdirectories at the next level of the current directory. If not, the returned array length is 0.

4, fileinfo[] di. GetFiles ();

Returns all sub-files at the next level of the current directory. If not, the returned array length is 0.

10.9. Path

The class is a path-related class, is a processing path string, it does not identify the file or directory, it will only identify the string, and then simply follow the string to deal with, it is all the functions of public static.

1, path.changeextension (string path,string extension);

This function is used to update the extension, path is the full path, and extension is the extension containing the sign-in period. If path does not have an extension, then add extension, and it will be updated directly. If extension is null or an empty string, then the extension in path is removed. This simply transforms the string and does not have any effect on the original file.

2, Path.getdirectoryname (string Path);

Path is either a file or a directory, which is the top-level directory of the returned file or directory, which is the string that precedes the last "\" symbol, or null if path is null or is the root directory.

3, Path.getextension (Stringpath);

Returns the extension with a leading period for the specified path. If there is no extension, a string of length 0 is returned. If path is NULL, NULL is returned.

4, Path.getfilename (string Path);

Gets the name of the file, including the extension, and, if it is a directory, is treated as a file. Path returns a string of length 0 if it is the root directory, or null if NULL.

1, Path.getfilenamewithoutextension (string Path);

Gets the name of the file that does not include the extension, and if it is a directory, it is treated as a file. Path returns a string of length 0 if it is the root directory, or null if NULL.

2, Path.GetFullPath (string Path);

Path is a relative or absolute path that returns an absolute path.

3, Path.getpathroot (string Path)

Gets the root directory information for path, and returns null if path is NULL.

10.10. Summary

Note: There are three times for any one of these files:

Creation time: The creation time of this file, if the file is copied to another path below, then the creation time of the file has changed, is the time of copying, if the file is renamed, then the creation time will not change.

Last modified: This time refers to the time when the contents of the file were last modified. If you copy this file to another path, the last modification time of the file will not change, and if you rename the file, the last modification time will not change. Only changes will be changed.

Last access time: Is the last time to access this file, this time is more ambiguous.

If you use a file A to overwrite file B with the same name, then B is overwritten, the creation time of B is unchanged, and the last modification time becomes the last modification time of a. The last time you modify a file, if you do not save, then the modification time is the original.

C # files and streams (FileStream, StreamWriter, StreamReader, file, FileInfo, Directory, DirectoryInfo, Path, Encoding)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.