The System.io namespace contains types that allow synchronization and asynchronous reading and writing on data streams and files.
The following differences help clarify the difference in documents and streams. The file is some ordered, named, have a collection of characters composed of permanently stored and specific sequences. Therefore, for documents, people often think of directory paths, disk storage, files, and directory names. In contrast, the stream provides a way to write bytes to the backup memory and the reading byte from the backup memory, and the backup memory can be one of a variety of storage media. As is a plurality of backup memories except the disk, there are also a variety of streams except for the file stream. For example, there is also a network stream, memory stream, and magnetic strip.
Basic file I / O
Abstract base class stream supports reading and writing bytes. Stream integrates asynchronous support. Its default implementation is defined according to its corresponding asynchronous method to define synchronous reading and writing, and vice versa.
All classes that represent streams are inherited from the stream class. The Stream class and its derived class provide the general view of the data source and repository, so that the programmer does not have to know the specific details of the operating system and the infrastructure.
Flow involves three basic operations:
Can be read from the stream. Read is data transfer from streaming to data structures (such as byte array).
You can write to the stream. Writing is a data transmission from the data structure to stream.
The stream can support find. Finding is a query and modification of the current location in the stream.
The stream may only support part of these functions depending on the underlying data source or repository. For example, NetWorkStreams does not support lookups. Stream's Canread, Canwrite, and Canseek properties and their derived classes determine how different streams are supported.
I / O class derived from System.Object
BinaryReader and BinaryWriter read from Streams or write to streams to the encoded string and the primitive data type.
FILE provides a static way for creating, copying, deleting, moving, and opening files and assists to create a FileStream object. The FileInfo class provides an example method.
Directory provides a static method for creating, moving, and enumerating through directory and subdirectories. The DirectoryInfo class provides an example method.
PATH provides methods and properties that handle directory strings in a cross-platform manner.
FILE, PATH and Directory are seals (in Microsoft Visual Basic) Class. You can create new instances of these classes, but they can be derived.
System.IO.FileSysteminfo and
FileSystemInfo is an abstract base class for FileInfo and DirectoryInfo objects.
FileInfo offers an instance method for creating, copying, deleting, moving, and opening files and assists in creating a FileStream object. The File class provides a static method.
DirectoryInfo provides an instance method for creating, moving, and enumerating through a directory and subdirectory. The Directory class provides a static method.
FileInfo and DirectoryInfo are seals (in Microsoft Visual Basic) Class. You can create new instances of these classes, but they can be derived.
Depends from System.io.Stream
FILESTREAM supports random access by its SEEK method. By default, FileStream opens files in synchronous mode, but it also supports asynchronous operations. File contains a static method, and FileInfo contains an example method.
MemoryStream is a non-buffered stream that can directly access its package data directly in memory. This stream does not have a backup memory, which can be used as a temporary buffer.
NetworkStream represents stream on your network. Although NetworkStream is derived from stream, it is not part of the system.io namespace, but in the system.net.sockets namespace. CryptostReam connects the data stream link to encryption conversion. Although CryptostReam is derived from stream, it is not part of the system.io namespace, but in the System.Security.cryptography namespace.
BufferedStream is a buffer stream to another stream (such as NetworkStream). (I have buffered inside the filestream, and MemoryStream does not need to buffer). The BufferedStream object can be composed of certain types of streams to improve read and write performance. The buffer is a byte block in memory for cache data, thereby reducing the number of calls to the operating system.
System.io.TextReader and its school
TextReader is an abstract base class for StreamReader and StringReader objects. Abstract Stream classes are implemented for byte input and output, while TextReader implementation is used for Unicode characters output.
StreamReader reads characters from streams by using eNCoding to convert characters in Streams. StreamReader has a constructor that attempts to determine the correct encoding for a given stream based on whether there is a preamble dedicated to Encoding (eg, one byte order marker).
StringReader reads characters from Strings. StringReader allows you to handle strings with the same API, so your output can be String or Stream in any encoded.
System.io.textwriter and
TextWriter is the abstract base class of StreamWriter and StringWriter objects. Abstract Stream classes are implemented for byte input and output, while TextWriter's implementation is used for Unicode characters output.
STREAMWRITER converts characters to bytes by using Encoding to streams.
StringWriter writes the strings to strings. StringWriter allows you to handle strings with the same API so that your output can be String or Stream in any encoded.
Enumetric number
FileAccess, FileMode, and Fileshare enumerates certain filestream and isolatedStorageFileStream constructor and certain file.open overload methods used constants. These constants affect how to create, open, and share underlying files.
The seekorigin enumeration number is defined to specify a constant that randomly accesses the file entry point. These constants are used with the byte offset.
I / O and security
When using classes in system.io namespace, to enable access to allow access, you must meet operating system security requirements such as access control list (ACL). This requirement is in the request of all FileiOperMissions.
WARNING The default security policy for Internet and intranet does not allow access to files. Therefore, if you write the code that will be downloaded through the Internet, do not use the "Regular" IO class. Please use independent storage.
WARNING When the file or network stream is turned on, the security check is only executed when the construction stream is constructed. Therefore, when these threads are sent to code or application domains, please be careful.
Create a list of directory
The following code example shows how to use the IO class to create a list of directories.
[C #]
Using system;
Using system.io;
Class DirectoryLister
{
Public static void main (string [] args)
{
DirectoryInfo Dir = New DirectoryInfo (".");
FOREACH (FileInfo F in Dir.Getfiles)))
{
String name = f.fullname;
Long size = f.length;
DateTime CreationTime = f.creationTIME;
Console.WriteLine ("{0, -12: N0} {1, -20: g} {2}", size,
CreationTime, Name);
}
}
}
In this example, the DirectoryInfo object is the current directory, with ("."), The code lists all files with the .cs extension in the current directory, and lists the size, creating time, and names of these files. Suppose there is a plurality of .cs files in the C: / MyDir / bin subdirectory, the output of the code may be as follows:
953 7/20/2000 10:42 AM C: /MYDIR/bin/paramatt.cs
664 7/27/2000 3:11 PM C: /MYDIR/BIN/TST.CS
403 8/8/2000 10:25 am c: /mydir/bin/dirlist.cs
If you want a list of files in another directory, such as a C: / root directory, remember to use a backslash (/) escape, such as the backslash in "C: //". You can also use the slash of the UNIX style, such as slash in "C: /".
Read and write data files you just created
BinaryWriter and BinaryReader class are used to read and write data instead of a string. The following code example demonstrates writing data to the new, empty file stream (Test.Data) and reading data from that file. After creating a data file in the current directory, the associated binarywriter and binaryReader, binarywriter are used to write integers 0 to 10 to Test.Data, and Test.Data leave a file pointer at the end of the file. After setting the file pointer back to the initial position, binaryReader reads the specified content.
[C #]
Using system;
Using system.io;
Class myStream {
Private const string file_name = "Test.data";
Public static void main (String [] args) {
// CREATE The New, Empty Data File.
IF (file.exists (file_name)) {
Console.writeline ("{0} already exissrs!", File_name);
Return;
}
FILESTREAM FS = New FileStream (file_name, filemode.createNew);
// Create The Writer for Data.
BinaryWriter W = New BinaryWriter (FS);
// Write Data to Test.data.
For (int i = 0; I <11; i ) {w.write (int) i);
}
W. close ();
fs.close ();
// Create The Reader for Data.
FS = New filestream (file_name, filemode.open, fileaccess.read);
BinaryReader R = New BinaryReader (FS);
// read Data from test.data.
For (INT I = 0; i <11; i ) {
Console.writeline (R.Readint32 ());
W. close ();
}
}
}
If Test.Data already exists in the current directory, an IOEXCEPTION is triggered. Always create new files with FileMode.create without triggering ioException.
Open and attach to log files
StreamWriter and StreamReader written into the characters and tanked from the stream. The following code example opens the log.txt file (if the file does not exist, create a file) for input and attach the information to the end of the file. Then write the contents of the file to the standard output to display it.
[C #]
Using system;
Using system.io;
Class Dirappend
{
Public static void main (string [] args)
{
StreamWriter W = file.appendtext ("log.txt");
LOG ("Test1", W);
LOG ("Test2", W);
// Close The Writer and Underlying File.
W. close ();
// Open and read the file.
StreamReader r = file.opentext ("log.txt");
Dumplog (r);
}
Public Static Void Log (String LogMessage, TextWriter W)
{
W.Write ("/ R / NLog Entry:");
w.writeLine ("{0} {1}", DateTime.now.tolongTimeString (),
DateTime.now.tolongDatestring ());
w.writeLine (":");
w.writeLine (": {0}", logmessage);
W.writeline ("--------------------------");
// Update the underlying file.
w.flush ();
}
Public Static Void Dumplog (StreamReader R)
{
// while not at the end of the file, read and write lines.
String line;
While (Line = R.Readline ())! = null)
{
Console.writeLine (LINE);
}
R.Close ();
}
}
Read text from the file
The following code example reads the entire file and issues a notification at the end of the file.
[C #]
Using system;
Using system.io;
Public class textfromfile {
Private const string file_name = "myfile.txt"; public static void main (String [] args) {
IF (! file.exists (file_name)) {
Console.writeLine ("{0} does not exist!", File_name);
Return;
}
StreamReader SR = file.opentext (file_name);
String input;
While ((Input = sr.readline ())! = null) {
Console.writeLine (Input);
}
Console.writeline ("The end of the streen reached.");
sr.close ();
}
}
This code creates a StreamReader pointing myFile.txt by calling file.opentext. StreamReader.Readline returns each line to a string. When there is no character to read, a message displays the situation and then the stream is turned off.
Write the text to the file
The following code example creates a new text file and writes a string.
[C #]
Using system;
Using system.io;
Public class texttoft {
Private const string file_name = "myfile.txt";
Public static void main (String [] args) {
IF (file.exists (file_name)) {
Console.writeline ("{0} already exissrs!", File_name);
Return;
}
StreamWriter SR = file.createtext (file_name);
Sr.writeline ("this is my file.");
Sr.writeline ("i can write {0} or floats {1}, and so on.",
1, 4.2);
sr.close ();
}
}
Read characters from strings
The following code example allows you to read a certain number of characters from the specified location in the existing string. Use StringReader to do this, as shown below.
The code defines the string and converts it into a character array, then you can read the character array as needed using the appropriate StringReader.Read method.
[C #]
Using system;
Using system.io;
Public Class Charsfromstr
{
Public static void main (string [] args)
{
// Create a string to read characters from.
String str = "some number of characters";
// size the array to hold all the characters of the string,
// SO That They is all accessible.
CHAR [] B = New char [24];
// Create a StringReader and attach it to the string.
StringReader SR = New StringReader (STR);
// r r car t f s, stout
// from the first array member.sr.read (b, 0, 13);
// display the output.
Console.WriteLine (b);
// Close The StringReader.
sr.close ();
}
}
This example reads only the specified number of characters from the string, as shown below.
Some Number O