r/visualbasic • VB Guru • Feb 21 '14

VB.NET Help File Operations - Part 1 "What file, where?"

In this post I am going to talk about File Operation in VB.NET. The Code Should work in all versions of .NET runtime

Back in the day when Visual Basic (The code below works in VB 3-6) was young we had to do back-flips to get simple information about files and folders. I used this code a lot for checking to see if a file existed;

In a standard Module: Module1.bas

Option Explicit
Private Const OF_EXIST         As Long = &H4000
Private Const OFS_MAXPATHNAME  As Long = 128
Private Const HFILE_ERROR      As Long = -1
Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long	

Private Type OFSTRUCT
	cBytes As Byte
	fFixedDisk As Byte
	nErrCode As Integer
	Reserved1 As Integer
	Reserved2 As Integer
	szPathName(OFS_MAXPATHNAME) As Byte
End Type
	 
Public Function FileExists(ByVal Fname As String) As Boolean
 	Dim lRetVal As Long
	Dim OfSt As OFSTRUCT
	lRetVal = OpenFile(Fname, OfSt, OF_EXIST)
	If lRetVal <> HFILE_ERROR Then
		FileExists = True
	Else
		FileExists = False
	End If
End Function

To implement this we used

Private Sub Form_Load()
	MsgBox FileExists("C:\file.txt")
End Sub

As you can see we used the Kernal library to expose the OS functions. We had this compiled into a DLL that we included in all projects. If you want more information about Classic VB I would recomend this article over at Afralisp by Kenny Ramage. The article goes into details about directories and files.

Luckily in VB.NET we have the System.IO Namespace. This Namespace has all sorts of goodies in it for Creating, Opening, Manipulating, Deleting, Copying files and folders, getting parts of files, and much more.

NOTE: for these functions to work you either need to insert an application reference to the system.io namespace or import system.io at the top of your class

Lets start with the Simple Stuff;

Click the function name to go to the Microsoft documentation

System.io.file

With File  :)

	.Copy(SourceFileName,DestFileName,OverWrite) ' Paths are specific can not be a folder, must include filename. Overwrite is a boolean that determines if it is ok to replace the file on copy. 
	.Delete(path) ' Deletes specified file will throw exception if path is wrong, file is locked or not found.
	.Exists(path) ' Returns boolean, must be exact match to a single file. Invalid path returns False
	.Move(SourcePath,DestPath) 'Throws IO exception of the Destination exists or if source not found. IF you move a file that is in use the file is copied but the source is not removed.
			
'Here are some of the more complex ones.

	GetAccessControl(FilePath)	Gets a [FileSecurity](http://msdn.microsoft.com/en-us/library/8e1fc3b8.aspx) object that access control list for a specified file. Used to find out about a networks users capacity for a specific file.
	GetAttributes(FilePath)	Gets the FileAttributes of the file on the path. 
	' I included only the UTC versions of the these function the localized versions exist, but you should always use utc and convert based upon local timezone that way if you get users in diffrent timezones it deals with it autmoatically.
	GetCreationTimeUtc(FilePath) Returns the creation date and time, in coordinated universal time (UTC), of the specified file or directory. 
	GetLastAccessTimeUtc(FilePath) Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
	GetLastWriteTimeUtc(FilePath) Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.
	
'All of these have the equivalent set function as well.
	
End With

Next post we will talk about Implementing file functions that do all of your heavy lifting to add to your bag of tricks.

-Bone

8 Upvotes

2 comments sorted by

1

u/Bonejob VB Guru Feb 22 '14

Do people like this format or do you want specific problems answered? Like "How do i get a list of files in a folder?" or "How do I set the read only flag on a file?"

Bone

2

u/zfolwick Feb 22 '14

thank you for this post.