. NET Getting Started VB article: File actions in Visual Basic.NET (i)

Source: Internet
Author: User
Tags chr expression file size file system integer numeric value object model valid
There are three ways to access the file system in visual Visual Basic.NET: The first is to use the Visual Basic run-time functions for file access (VB traditional way direct file access); NET and the third is the FSO access through the file system Object Model (System.IO).

A file is a collection of data stored on a piece of media, which in itself is simply a series of related data bytes on disk. When an application accesses a file, it must assume that the byte represents a character, a data record, an integer, a string, and so on. Tells the application what to assume by specifying the access type of the file.

Visual Basic provides three types of file access:

1. Order, which is used to read and write text files in contiguous blocks.

2. Random, used to read and write text or binary files with a fixed-length record.

3. Binary, used to read and write files of any structure.



Using Visual Basic run-time functions for file access



Vb. NET retains the early direct file access of VB, that is, to access the operation files directly through some related functions. The following table lists all available file access functions for three types of direct file access.

Function
Order
Random
Binary system
Description

FileOpen function
X
X
X
Open an input or output file

FileClose function
X
X
X
Close the file opened with the FileOpen function

Input function
X

X
Reads data from an open sequential file and assigns the data to a variable.

inputstring function
X


return String value

LineInput function
X


Reads a row of data from an open sequential file and assigns it to a String variable.

Print, PrintLine functions
X


Writes formatted display data to a sequential file.

Write, WriteLine functions
X


Writes data to a sequential file.



To manipulate a file, first open the file and use the FileOpen function.

Example: Open the Readme.txt file under C disk in Output mode sharing.

FileOpen (1, "C:\readme.txt", Openmode.output, openshare.shared)

When the operation file is finished, you need to close the file to prevent the loss of the contents of the file, in addition to the need to reopen the file also need to close the file, with the FileClose function, close the file opened just now C:\readme.txt:

FileClose (1);

When you open a sequential file in input mode, the file you want to open must already exist, or an error opens, and when you open a nonexistent file in output or append mode, FileOpen first creates the file and then opens it.

Some of the other functions:

Dir function: Returns a string representing a file name, directory name, or folder name that matches the specified pattern or file attribute, or a string that returns a drive volume label.

EOF function: Returns a Boolean value True when the end of a file that is opened in Random or sequential Input mode is reached.

FileCopy function: Copying files

FileDateTime function: Returns a date value indicating when and when a file was created or last modified.



FileLen function: Returns a Long value that specifies the length of the file in bytes.

FreeFile function: Returns an Integer value that represents the next file number that can be used by the FileOpen function.

GetAttr function: Returns the FileAttribute value representing the properties of a file, directory, or folder.

Loc function: Returns a Long value that specifies the current read/write location in the open file.

LOF function: Returns a Long value that represents the size, in bytes, of the file opened with the FileOpen function.

Seek function: Returns a Long value specifying the current read/write position in a file opened with the FileOpen function, or setting the location of the next read/write operation in a file opened with the FileOpen function.

SetAttr Function: Sets file property information.

1, the operation of sequential files

Reading a string from a file

There are three functions that can read strings from a sequential file: Input,inputstring and LineInput.

Input function

Reads data from an open sequential file and assigns the data to a variable.

Public Sub Input (filenumber as Integer, ByRef Value as Object)

Where the parameter filenumber is a valid file number, value is a variable given the value read from the file, it cannot be an array or an object variable.

The following example is a hello,world! example of writing and reading text example.txt, creating a new console application that writes the following code to view the results.

FileOpen (1, "C:\example.txt", Openmode.output)

Write (1, "Hello,")

Write (1, "world!")

FileClose (1)



Dim S as String

FileOpen (1, "C:\example.txt", OpenMode.Input)

Do with not EOF (1)

Input (1, s)

Console.WriteLine (s)

Loop

FileClose (1)

inputstring function

Returns a String value that contains the characters in a file that is opened in Input or Binary mode.

InputString (ByVal filenumber As Integer, ByVal charcount as Integer) as String

Where the parameter filenumber is a valid file number, CharCount is a valid numeric expression that specifies the number of characters to read.

Unlike the Input function, the InputString function returns all the characters it reads, including commas, carriage returns, line breaks, quotes, and leading spaces. For files opened in Binary access mode, an error is generated if you attempt to read the entire file with the InputString function before EOF returns TRUE. When reading binary files using inputstring, the LOF and LOC functions are substituted for the EOF function, and the FileGet function is used when using the EOF function.

Example:

Dim S as String

FileOpen (1, "C:\example.txt", Openmode.binary)

Do with not EOF (1)

s = inputstring (1, 9)

Console.WriteLine (s)

Loop

FileClose (1)

LineInput function:

Reads a row of data from an open sequential file and assigns it to a String variable.

Public Function LineInput (ByVal filenumber as Integer) as String

Parameter filenumber is a valid file number.

This function reads one character at a time from a file until it encounters a carriage return (CHR (13)) or carriage return-line feed (Chr + Chr (10)). Carriage return-The newline sequence is skipped rather than appended to the character string.

Example:

Dim S as String

FileOpen (1, "C:\example.txt", Openmode.binary)

Do with not EOF (1)

s = lineinput (1)

Console.WriteLine (s)

Loop

FileClose (1)



Write a string to a file

If you want to write data to a file, you can use the Print/printline function, if the data to be written is a string or a numeric value, you can use the Write/writeline function to write the file, you should first open the file in output or append mode, The menu can then use the print function or the Write function.

Print/printline function: Writes formatted display data to a sequential file.

Public Sub Print (ByVal filenumber as Integer, ByVal ParamArray Output () as Object)

Public Sub PrintLine (ByVal filenumber as Integer, Val ParamArray Output () as Object)

Where the parameter filenumber is a valid file number, Output is the 0 or more comma-delimited expression to be written to the file.

Example:

FileOpen (1, "C:\example.txt", Openmode.output)

PrintLine (1)

PrintLine (1, "Hello,")

Print (1,SPC (4), "world!")

FileClose (1)

Write/writeline and Print/printline are similar



2. Operation of random files

Random access to the bytes in the file constitutes the same number of records, each record contains one or more fields, and for a record of one field corresponds to any standard type, all records in the random Access file must have the same length, and if the actual string contains fewer characters than the fixed length of the string element to which it is written, the Visual Basic fills the trailing spaces in the record with white space (character code 32). If the string is longer than the field size, Visual Basic truncates it.

Example: User-defined data type:

Structure person

Public ID as Integer

Public Monthlysalary as Decimal

<vbfixedstring > Public Name as String

<vbfixedstring (2) > Public Sex as String

End Structure

Where vbfixedstring is used to define a string with a fixed length.

Before you open a file for random access, you should define a type of record that the type should contain or not include in the file.

To open a file for random access:

FileOpen function: FileOpen (filenumber, FileName, Openmode.random,,, RecordLength)

FileNumber and filename Specify the number and file name of the file to be opened, respectively. RECORDLENGTH specifies the size of each record in bytes. If the recordlength is less than the actual length of the record being written to the file, an error is generated.

Example: Open a randomly accessed file.

Dim FileNum as Integer, reclength as Long, Aperson as Person

' Calculate the length of the record

Reclength=len (Aperson)

' Get the available file number

Filenum=freefile ()

' Open File

FileOpen (FileNum, "C:\example.txt", openmode.random,,, Reclenght)

After you open the file, you can read the record into the variable and use the FileGet function.

Example: Reading the first record from a file

Dim FileNum as Integer, reclength as Long, Aperson as Person

Reclength=len (Aperson)

Filenum=freefile ()

FileOpen (FileNum, "C:\example.txt", openmode.random,,, Reclenght)

FileGet (filenum,aperson,1);

Console.WriteLine (aperson.id)

Console.WriteLine (Aperson.name)

Console.WriteLine (Aperson.sex)

Console.WriteLine (Aperson.monthlysalary)

FileClose (FileNum)



Write records: Replace existing or new records with the FilePut function

Example: Writing five records to a file:

' Custom data type

Structure person

Public ID as Integer

Public Name as String

End Structure

Sub WriteData ()
Dim Myrecord as Person
Dim recordnumber as Integer
' Randomly open.
FileOpen (1, "C:\example.txt", Openmode.binary)
For recordnumber = 1 to 5 '
Myrecord.id = RecordNumber ' Define ID.
Myrecord.name = "My Name" & recordnumber ' creates a string
FilePut (1, Myrecord) ' Write to File
Next recordnumber
FileClose (1)
End Sub
The above code enables random access to open the file and write the record.



Operation of binary files

Open the file you want to make binary access

FileOpen (FileNumber, FileName, Openmode.binary)

To close a file for binary access

FileClose (FileNumber)

If it is important to maintain a smaller file size, binary access is used. Because binary access does not require fixed-length fields, type declarations can omit string-length parameters. This allows you to conserve disk space by generating variable-length records. Types that use binary access are defined as:

Structure person

Dim ID As Integer

Dim Name As String

Dim monthlysalary As Decimal

Dim Sex As String

End Structure

The disadvantage of binary input/output using variable-length fields is that records are not accessed randomly, and they must be accessed sequentially to understand the length of each record. You can still go directly to the specified byte position in the file, but if the field is longer, you do not know which record is at which byte.

(partially translated from MSDN)


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.