Four Methods for Excel-VBA file operations (2)

Source: Internet
Author: User
Tags filetime readfile

(2) process files

The following are the APIs for file operations in windows and their functions:

Closehandle closes a kernel object. This includes file, file ing, process, thread, security, and synchronization objects.
Comparefiletime: Compare the time of the two files based on the filetime structure information.
Copyfile: copy the file. Note: Only files can be copied, but directories cannot be copied.
Createfile is a full-featured function that allows you to open and create files, pipelines, mail slots, communication services, devices, and the console.
Deletefile: delete a specified file
Findclose closes a search handle created by the findfirstfile function.
Findfirstfile
Findnextfile searches for the next file based on a file name specified when the findfirstfile function is called.
Flushfilebuffers refreshes the internal file buffer for the specified file handle
Getbinarytype determines whether the file can be executed
Getfileattributes determines the attributes of a specified file
Getfileinformationbyhandle: this function can obtain the information that all functions above can obtain, such as the size and attribute. It also includes information that cannot be obtained elsewhere, for example: file tag, index, and link information.
Getfilesize determines the file length
Getfiletime obtains the time information of the specified file. There are three file times: creation time, last access time, and last write time.
Getfiletype: determines the file type while giving the file handle.
Getfileversioninfo obtains the file version information from a module that supports version tagging.
Getfileversioninfosize determines the size of a buffer zone for a file containing version Resources
Getfullpathname: get the file path. This function obtains the complete path name of the file. Note: Only when the file is in the current directory,
The result is correct. If you want to get the real path. Use the getmodulefilename function.
Getshortpathname: Get the short path name of the specified file
The gettempfilename function contains the name of a temporary file, which can be used by applications.
Gettemppath: Get the Windows temporary directory path
Lclose to close the specified file. Refer to the closehandle function for more information.
Lcreat creates a file. If the file already exists, it will be shortened to zero length and opened for read/write
Llseek sets the current position for reading and writing in the file. This function is similar to the seek Statement of VBA.
Lockfile is available in Shared Mode in windows. In this case, multiple processes can access the file at the same time.
With this function, an application that needs to read and write files can lock a part of the file to make it
Cannot be accessed by other applications. This avoids conflicts during simultaneous read/write operations.
Lockfileex is similar to lockfile, but it provides more functions.
Lopen opens the specified file in binary mode.
Lread reads data from files into the memory buffer.
Lwrite writes data from the memory buffer to a file
Movefile and movefileex move the file. If dwflags is set to zero, movefile is equivalent to movefileex.
The openfile function can perform a large number of different file operations. Compared with this function, consider the createfile function first.
(It can open named pipelines and control Unicode file names without the restriction of path names with 128 characters)
Readfile reads data from the file. Compared with the lread function, this function is much more flexible. This function can operate
Communication devices, pipelines, sockets, and mail Slots
Readfileex is similar to readfile, but it can only be used for asynchronous read operations and contains a complete callback.
Searchpath
Setendoffile sets the current file location to the end of the file for an opened file
Setfileattributes
Setfilepointer sets the current read/write location in a file
Setfiletime: Set the file creation, access, and last modification time.
Unlockfile unlocks a file
Unlockfileex unlocks a file
Writefile writes data to a file. This function is more flexible than the lwrite function. You can also apply this function
Handling of communication devices, pipelines, sockets, and mail Slots
Writefileex is similar to writefile, but it can only be used for asynchronous write operations and includes a complete callback.

File compression and decompression

Lzopenfile open the compressed file to read
Lzseek searches for a location in the compressed file
Lzread reads a compressed file.
Lzclose close a compressed file
Lzcopy copies the compressed file and expands it during processing
Getexpandedname returns the file name from the compressed file.

The following describes the main functions and their usage through several examples:

1. createfile

Role: This is a full-featured routine that allows you to open and create files, pipelines, mail slots, communication services, devices, and the console.

Statement:
Declare function createfile lib "Kernel32" alias "createfilea" (byval lpfilename as string, byval dwdesiredaccess as long, byval dw1_mode as long, lpsecurityattributes as security_attributes, byval dwcreationdisposition as long, byval dwflagsandattributes as long, byval htemplatefile as long) as long

Note:
The Return Value Type of this function is long. If the execution is successful, the file handle is returned. Invalid_handle_value indicates an error and getlasterror is set. Even if the function succeeds, if the file exists and create_always or open_always are specified, getlasterror is set to error_already_exists.

When you open a communication port (such as COM1), you must set it to open_existing in any case.

This function replaces lopen and lcreate functions and should be our first choice.

Parameter description:

· Lpfilename string: name of the file to be opened
· Dwdesiredaccess long. If generic_read is used, read access to the device is allowed. If generic_write is used, write access to the device is allowed (can be used in combination). If it is set to zero, indicates that only information related to one device can be obtained.
· Dw1_mode long. Zero indicates that files are not shared. file_1__read and/or file_1__write indicate that shared access to files is allowed.
· Lpsecurityattributes security_attributes, which points to a security_attributes structure pointer and defines the file security features (if supported by the operating system)
 
· Dwcreationdisposition
Long, one of the following constants:
Create_new: Creates a file. If the file exists, an error occurs.
Create_always: Creates a file and changes the previous file.
The open_existing file must already exist. Requirements from devices
Open_always: Create an open_always file if it does not exist.
Truncate_existing indicates that the existing file is shortened to zero length.

· Dwflagsandattributes
Long, one or more of the following Constants
File_attribute_archive mark archive attributes
File_attribute_compressed marks the file as compressed, or marks it as the default compression mode of the file in the directory.
File_attribute_normal default attribute
File_attribute_hidden: hide a file or directory
The file_attribute_readonly file is read-only.
The file_attribute_system file is a system file.
The file_flag_write_through operating system must not postpone file write operations.
File_flag_overlapped allows overlapping operations on files
File_flag_no_buffering prohibits file caching. The file can only be written into the Sector blocks of the disk volume.
File_flag_random_access optimizes the File Buffer for Random Access
File_flag_sequential_scan optimizes the File Buffer for continuous access
File_flag_delete_on_close closes the last opened handle and deletes the file. Especially suitable for temporary files
You can also combine the following constant tags in Windows NT:
Security_anonymous, security_identification, security_impersonation, security_delegation, security_context_tracking, security_inclutive_only
 
· Htemplatefile long. If it is not zero, a file handle is specified. The new file will copy the extended attributes from this file.

Example:

Lnghandle = createfile ("C:/text.txt", generic_write, file_1__read or file_1__write, byval 0 &, open_always, 0, 0)

'The code above opens the file as a write method. If the file does not exist, create it.

2. lcreat

Purpose: create a file. If the file already exists, it will be shortened to zero length and opened for read/write

Declaration: declare function lcreat lib "Kernel32" alias "_ lcreat" (byval lppathname as string, byval iattribute as long) as long

Description: The Return Value Type of this function is long. If the execution is successful, a handle to open the file is returned. If an error occurs, hfile_error is returned.

This function will open files opened by other applications, so be careful when using it. The createfile function of Win32 has replaced this function. This function works the same as the open statement of VB.

Parameter description:

Lppathname string, name of the file to be created
Iattribute long, one of the following values:

0 -- the file can be read and written
1 -- create a read-only file
2 -- create a hidden file
3 -- create a system file
 
Example:
The following statement opens the C:/test.txt File

Lcreat "C:/test.txt", 0

3. lopen

Purpose: open a specified file in binary mode.

Declaration: declare function lopen lib "Kernel32" alias "_ lopen" (byval lppathname as string, byval ireadwrite as long) as long

Description: The Return Value Type of this function is long. If the execution is successful, a handle to open the file is returned. Hfile_error indicates an error. Getlasterror is set.

Parameter description:

Lppathname string, name of the file to be opened
Ireadwrite long, a combination of the access mode and the shared mode constant, as shown below:
1. Access Mode
Read: open the file and read the content.
Read_write open the file and read and write it
Write: open the file and write the content in it.
2. Sharing Mode (refer to the mark constant table of the openfile function)
Of_share_compat, of_share_deny_none, of_share_deny_read, of_share_deny_write, of_share_exclusive

Example:
Lopen "C:/test.txt", read

4. getfiletime

Purpose: Obtain the time information of the specified file.

Declaration: declare function getfiletime lib "Kernel32" alias "getfiletime" (byval hfile as long, lpcreationtime as filetime, lplastaccesstime as filetime, lplastwritetime as filetime) as long

Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set.

If you do not need specific information, you can set the value of lpcreationtime, lplastaccesstime, and lplastwritetime to zero (byval as long ). The file time returned by this function is in UTC format.

Parameter description:
Hfile long, file handle
Lpcreationtime filetime, used to load the File Creation Time
Lplastaccesstime filetime, used to load the last file access time (this feature is not supported by the FAT file system)
Lplastwritetime filetime, used to load the last modification time of the file

Example:

Dim file as long
Dim creationtime as filetime
Dim lastaccesstime as filetime
Dim lastaccesstime as filetime
'Define the structure
Private type filetime
Dwlowdatetime as long
Dwhighdatetime as long
End type

Str1 = "C:/text.txt"
File = lopen (str1, read_write) 'open the file
Temp = getfiletime (file, creationtime, lastaccesstime, lastwritetime )'

The time information obtained by the code above is long type, and the time conversion function is required for conversion. For a complete example, see the attachment.

5. copyfile

Purpose: copy an object. Similar to the filecopy command of VB

Declaration: declare function copyfile lib "Kernel32" alias "copyfilea" (byval lpexistingfilename as string, byval lpnewfilename as string, byval bfailifexists as long) as long

Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set.

Parameter description:

Lpexistingfilename string, source file name
Lpnewfilename string, target file name
Bfailifexists long. If it is set to true (non-zero), function call fails once the target file already exists. Otherwise, the target file is rewritten.

Example:
Copyfile "C:/test1.txt", "C:/test2.txt", 1

The above code copies C:/test1.txt to C:/test2.txt. For the complete example, see the attachment.

6. movefile and movefileex

Function: Move a file. If dwflags is set to zero, movefile is equivalent to movefileex.

Statement:
Declare function movefile lib "Kernel32" alias "movefilea" (byval lpexistingfilename as string, byval lpnewfilename as string)

Declare function movefileex lib "Kernel32" alias "movefileexa" (byval lpexistingfilename as string, byval lpnewfilename as string, byval dwflags as long)

Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set.

These two functions generally cannot move files from one volume to another. If the movefile_copy_allowed flag is set, movefileex can do this.

Parameter description:

Lpexistingfilename string, name of the file to be moved
Lpnewfilename string, new file name
Dwflags long, one or more of the following Constants
Movefile_replace_existing Replace the target file if it exists.
If movefile_copy_allowed is moved to a different volume, copy the file and delete the original file.
The movefile_delay_until_reboot mobile operation is officially started the next time the system restarts. In this way, you can change the system file in Windows NT

Example:
Private const movefile_copy_allowed = & H2
Private const movefile_delay_until_reboot = & h4
Private const movefile_replace_existing = & H1

Movefile "C:/test.txt", "d:/test1.txt" 'Move the file
Movefileex "D:/test1.txt", "C:/test.txt", movefile_copy_allowed 'Move again

The above code moves the file. After two moves, the file remains unchanged.

7. deletefile

Purpose: delete a specified file.

Declaration: declare function deletefile lib "Kernel32" alias "deletefilea" (byval lpfilename as string) as long

Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set.

Similar to the kill Statement of VBA, be careful when using this function in Windows 95-this function will delete a file even if it is being opened by an application.

Parameter description:
Lpfilename string, name of the object to be deleted

Example:

Deletefile "C:/test.txt" 'Delete the C:/test.txt File

For a complete example, see the attachment.

8. readfile

Purpose: read data from a file. Compared with the lread function, this function is much more flexible. This function can be used to operate communication devices, pipelines, sockets, and mail slots.

Declaration: Private declare function readfile lib "Kernel32" alias "readfile" (byval hfile as long, lpbuffer as any, byval stored as long, lpnumberofbytesread as long, lpoverlapped as overlapped) as long

Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set. If an asynchronous read operation is started, the function returns a zero value and sets error_io_pending to getlasterror. If the result is not zero, but the number of bytes read is smaller than the value specified by the nnumberofbytestoread parameter, it indicates that the end of the file has been reached.

Parameters:
Hfile ---- long, file handle
Lpbuffer --- Any, used to save a buffer for reading data
Nnumberofbytestoread-long, number of characters to read
Lpnumberofbytesread-long, number of characters actually read from the file
Lpoverlapped --- overlapped. If you specify file_flag_overlapped when opening a file, you must use this parameter to reference a special structure. That structure defines an asynchronous read operation. Otherwise, set this parameter to null (declare the function as byval as long and pass the zero value)

Example: For the complete example, see the attachment.

9. writefile

Purpose: write data into a file. This function is more flexible than the lwrite function. This function can also be used to process communication devices, pipelines, sockets, and mail slots.

Declaration: declare function writefile lib "Kernel32" alias "writefile" (byval hfile as long, lpbuffer as any, byval nnumberofbytestowrite as long, stored as long, lpoverlapped as overlapped) as long

Note: Long, true (non-zero) indicates successful; otherwise, zero is returned. Getlasterror is set.

Parameters:
Hfile --- long, the handle of a file
Lpbuffer --- any, a data buffer to be written
Nnumberofbytestowrite-long, number of bytes to write data. If the value is written to zero bytes, it indicates that nothing is written, but the "last modification time" of the file is updated ". For named pipelines located in remote systems, the limit is less than 65535 bytes.

Lpnumberofbyteswritten-long, number of bytes actually written to the file

Lpoverlapped --- overlapped. If you open a file while specifying file_flag_overlapped, this parameter must reference a special structure. That structure defines an asynchronous write operation. Otherwise, this parameter should be left blank (change the Declaration to byval as long and pass the zero value)

Example: For the complete example, see the attachment.

10. shfileoperation

Function: this function is powerful and can copy, move, rename, and delete files or folders.

Declaration: declare function shfileoperation lib "shell32.dll" alias "shfileoperationa" (lpfileop as shfileopstruct) as long

Note: Long, true (non-zero) indicates successful; otherwise, zero is returned.

Parameters:
Lpfileop -- shfileopstruct type, specifies the file operation.
Type shfileopstruct
Hwnd as long
Wfunc as long 'command for file operations
Pfrom as string' source file or path
PTO as string 'destination file or path
Fflags as Integer Operation flag
Fanyoperationsaborted as long
Hnamemappings as long
Lpszprogresstitle as string
End type

Example: see the attachment.

(3) Summary

Through the above introduction, we can see that the API is very powerful in file operations and can complete tasks that cannot be completed by the previous method. The FileSystemObject object model may be written using APIs. Even if it is not, you can use APIs to write an fso class. API is a huge treasure. When you are not able to implement a function, you may find a satisfactory answer by checking the API.

If you write so much, I hope it will be helpful to everyone. At least there is no problem in file operations.

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.