When you first read and write files with VB.NET, you will definitely find that VB.NET has abandoned traditional file I / O support and feels not used to it. In fact, in .NET, Microsoft replaces traditional file operations with rich "flow" objects, and "flow" is an object that is often used in UNIX.
We can treat the stream as a channel, the data of the program can be "stream" to various data storage mechanisms along this channel (such as files, strings, arrays, or other forms). Why do we abandon your IO operations, and the generation is current? One of the most important reasons is not all the data exists in the file. Now programs, get data from various types of data stores, such as a file, buffer in memory, and Internet. Streaming technology allows applications to obtain various data based on a programming model, without having to learn how to get specific techniques for a file on the remote web server. We only need to create a stream between the application and the web server, and then read the data sent by the server.
Streaming objects, various operations that encapsulate the read and write data sources, the biggest advantage is that when you do a certain data source, you can extend this technique to other shapes of data sources.
Cyber
The stream is an abstract class that you cannot declare a instance of Stream in the program. In .NET, five specific streams were derived from Stream, which is FileStream supports the order of files and random read and write operations MemoryStream supports the order and random read and write operations of the memory buffer networkStream support the order of Internet resources. Random read and write operation, existing in system.net.sockets namespace CRYPTOSTREAM support data encoding and decoding, existing in system.security.cryptography namespace BufferedStream support buffer read and write to those who are not supported
Not all stream uses the same method as fully touching, such as the stream of the local file, can tell us the length of the file, the location of the current read and write, etc. You can use the Seek method to jump to the file. Instead, these features are not supported by reading the stream of remote files. However, Stream itself has the Canseek, Canread and CanWrite properties for distinguishing data sources, telling us that support is still in a certain characteristic.
Below we briefly introduce a FileStream class
When the FileStream class performs a local file operation, we can use the FileSteam class, which can be readily read and written as an arrays of bytes. For simple data types of data read and write, BinaryReader and BinaryWriter and StreamReader, Streamwriter class can be used. BinaryReader, read the primary data type by a specific code to binary values. BinaryWriter writes the current type in binary form to stream and supports a specific encoding write string. StreamReader / Writer is stored in XML format. The difference is not large in VB.NET, because the classes used are applied to two formats.
VB.NET supports traditional random read and write files, you can create files for storing Struct and then access according to record number. Just like in previous VB versions, use FileOpen, Fileget functions. To a large extent, this has been replaced by XML or database. If you create a new application, there is no need to consider compatibility with the version, it is recommended to use the new features of .NET.
Whether you have to use a streamclass, you must create a FILESTREAM object. There are many ways to create, the simplest is to specify the file path, open the mode, such as the syntax below. DIM FSTREAM As New FileStream (Path, FileMode, FileAccess)
Path To include the path of the file and the file name. FileMode is one of the members of the enumeration type FileMode, as shown in the following table. FileAccess is a member of enumeration type FileAccess. Readwrite, READWRITE (Write), and WRITE. Decided to read and write the file.
Specifies the operating system to create a new file. If the file already exists, it will be rewritten CreateNew Specifies the operating system to create a new file. Open Specifies the operating system to open an existing file. Openorcreate Specifies the operating system to open the file (if the file exists); otherwise, a new file should be created. Truncate Specifies the operating system to open an existing file. Once the file is opened, it will be truncated to zero byte size. Of course, you can also create fileStreams (Open, OpenRead, OpenText, OpenWrite). DIM FS AS New FileStream = IO.File.OpenWrite ("c: /stream.txt") Another way to open the file with the OpenFile method of the OpenFileDialog and SaveFileDialog control. You don't need to specify any parameters. OpenFileDialog's OpenFile method opens a file in read-only mode; SaveFileDialog's OpenFile method opens files in reading and writing. FileStream only supports the most basic operations, writing data to byte arrays or writes from byte arrays. If we save the data in a file with FileStream, you first convert the data to a BYTE array, then call the FileStream's Write method. Similarly, the FileStream's Read method returns the byte array. You may not always use the FileStream object directly, we still need to simply look at its basic function After creating a FileStream object, call WRITEBYTE to write a byte into the file. The Write method can write an array to files, require three parameters Write (buffer, offset, count) buffer to write an array address, offset is offset, count refers to the number of bytes, the syntax of the read . Since FileStream is to deal with bytes array, study ASCIENCODING Gettes and UnicodeEncoding getchars must be necessary The following example is a conversion operation. Dim buffer () AS BYTE DIM Encoder as new system.text.asciiencoding () DIM STR As String = "this is a line of text" Redim buffer (str.length - 1) Encoder.getbytes (Str, 0, Str.length, Buffer, 0) Fs.write (buffer, 0, buffer.length) Note: The BYTE array to be written to be written is the length of the read and write. Document operation specific example In this section, you will find more commonly used code instances. The most commonly used, the most basic operation is to write Text into files and read back. The current application usually does not have a binary file to store simple variables, and it is used to store objects, object gathers, and other machine code. Next, an example of the specific operation will be seen. Flexible and diverse IO operation Sometimes, the conversion between the data and byte arrays is a cumbersome thing. In order to avoid these bored conversion and simplifying the code, StreamReader / streamwrite and binaryreader / binarywriter are not wise. StreamReader / streamWrite is derived by the TextReader / TextWriter class, automatically performs the conversion of byte encoding. BinaryReader / BinaryWriter is derived from stream, mainly read and write data in binary form. When reading data from binary file, first create a BinaryReader instance, BinaryReader's build function accepts a FileStream object, which represents the file to be read. We have already seen before we can create a FileStream object with File.OpenRead or File.OpenWrite methods. As follows: Dim br as new o.binaryreader (IO.FILE.Openread (PATH)) DIM BW As new Io.binaryWriter (IO.FILE.OpenWrite (PATH)) BinaryWriter class has two methods of WRITE and WRITELINE, can accept any type of data as a parameter write file (WriteLine adds a line of data at the file). The BinaryReader class has a lot of read data. When the data is stored on the file, there is no information about the type of information, so when reading the data, the appropriate overloaded Read method must be selected. The following example assumes that BW is a binarywriter object that has been initialized, indicating how to write a string, integer, double precision number to file: BW.WRITELINE ("a string") BW.WRITELINE (12345) Bw.writeline (123.456789999999) When reading back the data, you must choose a BinaryReader suitable Read method: DIM S as string = br.ready 4tring () DIM I as int32 = br.readint32 () DIM DBL AS DOUBLE = Br.Readdouble () For text files, the StreamReader / StreamWriter object is used. The method is similar to the above, and write data is also used by WRITE and WRITELINE methods. Readline reads a character, readline reads a line of data (until the Enter / Finite is available), readtoend reads all characters, and ends to the file. Object sequence So far, we just write simple type data to the file and read back the program. In fact, most programs read and written may not be simple type, but complex structures, such as: arrays, array lists, hash tables, etc. So, we take a sequential technology that first transforms the value of the array into a byte sequence, then writes the file, so that the entire array is stored. Instead, we call it anti-sequence. Serialization is a big topic for .NET, this column introduces basic information. Save an object to the file and read the program with binary systematter's Serialize and DeSerialize methods. First, Imports System.Runtime.Serialization.Formatters can be removed so long. The Formatters name space contains a BinaryFormatter class for use in binary data serialization. Create a BinaryFormatter instance, then call the serialize method, serialize accepts two parameters: one is a writable FileStream instance for saving the file; the other is the object itself: DIM BINFORMATTER As new binary.binaryformatter () DIM R AS New Rectangle (10, 20, 100, 200) Binformatter.Serialize (fs, r) The DESERIALIZE method of BinaryFormatter has only one parameter, and the FileStream instance. In the current position, the reverse sequence is a type unknown object, we must convert to the original object with CType. The following example reflects the above file to get the original Rectangle object: DIM R as new rectangle () R = ctype (binformatter.deSerialize (fs), rectangle) We can also serialize in XMLFormatter. First, select Add System.Runtime.Serialization.Formatters.SoAP in the IDE's Project Menu, then you can create a SOAPFormatter object, the method is the same as binformatter, only the data store is used in XML format: DIM FS AS New IO.FILESTREAM ("C: /Rect.xml", IO.FILEMODE.CREATE, IO.FILEACCESS.WRITE DIM XMLFORMATTER AS New SOAPFORMATTER () DIM R AS New Rectangle (8, 8, 299, 499) XMLFormatter.Serialize (fs, r) Open C: /Rect.xml, actually stores these contents: - - - a1: Rectangle> Soap-env: body> Soap-env: envelope> Read and write text files In order to save Text to the file, create a FileStream-based StreamReader object, and then call the Write method to write the text required to save. The following code is prompted by SaveFileDialog prompting the user to specify a file to save the contents of TextBox1. SavefileDialog1.filter = _ "Text Files | * .txt | all files | *. *" SaveFileDialog1.FilterIndex = 0 If SavefileDialog1.ShowDialog = DialogResult.ok Then DIM fs as filestream = savefiledialog1.openfile DIM SW AS New StreamWriter (fs) SW.write (TextBox1.text) SW.CLOSE () Fs.close () END IF Similarly, similar statements, we read a text file and display the content in the TextBox control. StreamReader's readtoEnd method returns all the contents of the file. OpenFileDialog1.filter = _ "Text Files | * .txt | all files | *. *" OpenFileDialog1.FilterIndex = 0 If OpenFileDialog1.ShowDialog = DialogResult.ok then DIM FS AS FileStream FS = OpenFileDialog1.openfile DIM SR AS New StreamReader (FS) TextBox1.text = sr.readToeD Sr.close () Fs.close () END IF Storage of various objects A specific object can be serially used in a binary form in binary form, or using the SOAPFormatter class in an XML format. As long as you change all binaryformatter to SOAPFormatter, you can serialize the object in an XML format without changing any code. First create a BinaryFormatter instance: DIM BINFORMATTER As new binary.binaryformatter () Then create a FileStream object for storing sered sequences: Dim fs as new system.io.filestream ("c: /test.txt", IO.FILEMODE.CREATE Then call the BinFormatter's Serialize method serialized any Framework object that can be serialized: R = new rectangle (rnd.next (0, 100), rnd.next (0, 300), _rnd.next (10, 40), Rnd.Next (1, 9)) Binformatter.Serialize (fs, r) Add a serializable property to make custom objects can be serialized DIM Name as String DIM AGE AS INTEGER DIM INCOME As Decimal End structure The following code creates a Person object instance, then call the BinFormatter's Serialize method serialized custom object: P = new person () P.Name = "Joe Doe" P.AGE = 35 P.income = 28500 Binformatter.Serialize (fs, p) You can also serialize other objects in the same stream, then read back in the same order. For example, after serializing the Person object, then serialize a Rectangle object: Binformatter.Serialize (FS, New Rectangle (0, 0, 100, 200))) Create a BinaryFormatter object, call its Deserialize method, and turn the return value to the correct type, which is the entire reverse sequence process. Then sequence the other objects of the Stream. Assuming that both of the Person and Rectangle have been seriallyified, in the same order, we can get the original object: DIM P as new person () P = binformatter.Serialize (fs, person) DIM R AS New Rectangle R = binformatter.serialize (fs, rectangle) Persisting Collectes Collection store Most programs handle object collections rather than individual objects. For collection data, first create an array (or other types of collection, such as arraylist or hashtable), populate with objects, and then a serialize method can serialize the true collection, is it simple? The following example first creates an ArrayList with two Person objects, then serialize itself: Dim fs as new system.IO.FileStream_ ("C: / Test.txt", IO.FILEMODE.CREATE) DIM BINFORMATTER As new binary.binaryformatter () DIM P as new person () DIM PERSONS AS New ArrayList P = new person () P.Name = "Person 1" P.AGE = 35 P.income = 32000 Persons.Add (P) P = new person () P.Name = "Person 2" P.AGE = 50 P.income = 72000 Persons.Add (P) Binformatter.Serialize (fs, person) With the file of the store serialized data, call a Binary Systematter instance's DeSerialize method, it will return an object and convert it into a suitable type. The following code is deserved in the file in all objects, then processes all Person objects: fs = new system.io.filestream_ ("C: / Test.txt", IO.FILEMODE.OPENORCREATE DIM OBJ AS Object DIM P as person (), R as Rectangle () DO Obj = binformatter.deSerialize (fs) IF Obj.gettype is gettype (person) THEN P = ctype (obj, person) 'Process the P Objext END IF Loop while fs.position Fs.close () The following example calls the Deserialize method to reverse sequencing true collections, then convert the return value to the appropriate type (Person): FS = new system.io.filestream ("c: /test.txt", ousfilemode.openorcreate) DIM OBJ AS Object DIM PERSONS AS New ArrayList Obj = ctype (binformatter.deSerialize (fs), arraylist) Fs.close ()