SlideShare a Scribd company logo
File Operations in Visual Basic 6


                    File Operations in Visual Basic 6
                    I'm frequently asked how to perform file operations in Visual Basic--for
                    instance, how to delete a file or create a directory or folder.

                    In this month's article, I'm going to show you five basic file type operations
                    using built in Visual Basic functions. These techniques are considered old
                    style by programmers familiar with Object Oriented programming who prefer
                    to use the File System Object (FSO). But a discussion of the F SO requires a
                    knowledge of Objects and Collections---perhaps I'll discuss FSO in a future
                    article, provided you promise to read my Objects book, Learn to Program
                    Objects with Visual Basic 6.

                    But back to File Operations using the built in Visual Basic functions to which I
                    alluded. We can categorize these operations in two ways: operations on files
                    and operations on directories, or the newer term, folders.

                    Copying Files

                    When you copy a file you keep the existing file, and make a copy of the file
                    with a new name. Visual Basic provides a statement for this called FileCopy.

                    Here's the syntax for the FileCopy statement

                    FileCopy source, destination

                    where source is the name of the file to copy, and destination is the name of
                    the copied file.

                    You have several choices when it comes to specifying the file names here---
                    you can use the full path names for the files, or you can just specify the name
                    of the files.

                    By way of background, Windows keeps track of something called the current
                    drive and the current directory for us---these are basically pointers in the File
                    System, and in the old days of DOS allowed us to perform mundane file
                    operations without having to specify the name of the Drive and the Directory.
                    These pointers still carry on in VB and Windows, so if we use this syntax in
                    the Click Event Procedure of a Command Button

                    Private Sub Command1_Click()

                    FileCopy "a.txt", "b.txt"


http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (1 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6



                    End Sub

                    Windows looks for a file called "a.txt" in the current drive and current directory
                    of our PC, and if the operating system finds it, copies the file as "b.txt", again
                    in the default drive and directory of the PC.

                    The problem here is that if the file is not found, your program bombs, just like
                    this…




                    The Current Drive and Current Directory

                    As it turns out, Visual Basic has a function that can be used to determine the
                    current directory called the CurDir function …

                    Private Sub Command2_Click()

                    MsgBox "The current directory is " & CurDir

                    End Sub




                    Changing the Current Drive and Current Directory


http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (2 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6


                    Once you know the current directory, you can then use the ChDir and
                    ChDrive functions to change either the current drive or the current directory,
                    like this…

                    Private Sub Command3_Click()

                    ChDrive ("d")
                    ChDir "vbfiles"

                    MsgBox "The current directory is " & CurDir

                    End Sub




                    Now if you are like me, you may not want to leave anything to chance, in
                    which case, you can use the full path name with the FileCopy statement, like
                    this…

                    Private Sub Command1_Click()

                    FileCopy "c:vbfilesa.txt", "c:vbfilesb.txt"

                    End Sub

                    I should mention that here that if you attempt to copy a file that is opened,
                    you'll receive this error message…




http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (3 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6




                    Does a file exist?

                    There's no confirmation that the copy was successful, but you can determine
                    if a file exists by using the Visual Basic Dir$ function. The Dir$ function
                    requires just a single argument representing the file name (as was the case
                    with the CopyFile statement, you can specify just the file name or the full path
                    name). If the file is found, then Dir$ returns the file name (not the full path). If
                    the file is not found, then Dir$ returns an empty string. Let's see how we can
                    use the Dir$ function to determine if a file exists before we copy it.

                    Private Sub Command1_Click()

                    Dim retval As String

                    retval = Dir$("c:vbfilesb.txt")

                    If retval = "b.txt" Then
                       MsgBox "b.txt exists--no need to copy it..."
                    Else
                       FileCopy "c:vbfilesa.txt", "c:vbfilesb.txt"
                    End If

                    End Sub

                    If we now run the program, and click on the command button…




http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (4 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6




                    We receive a message saying that the file already exists---Dir$ has done its
                    job.

                    By the way, you'll discover that there's a Dir function as well---Dir returns a
                    variant return value and Dir$ returns a string.

                    Renaming Files

                    Renaming files is similar to copying them--this time we use the Visual Basic
                    Name statement. Here's the syntax.

                    Name oldpathname As newpathname

                    As was the case when we copied files, we can choose either to specify a file
                    name or to include the full path name---once again, I advise the full path
                    name…

                    Private Sub Command1_Click()

                    Name "c:vbfilesb.txt" As "c:vbfilesnewb.txt"

                    End Sub

                    This code will result in the file 'b.txt' begin renamed to 'newb.txt'. Once again,
                    don't expect a confirmation message telling you that the rename was
                    successful--the only message you'll receive is if the file does not exist




http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (5 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6




                    Deleting Files

                    The final file operation I'll discuss in this article is that of deleting a file. Visual
                    Basic provides us with the Kill statement which will delete a file (and
                    dangerously, a wildcard selection of files) of our choosing. Here's the syntax…

                    Kill pathname

                    Let's say that we wish to delete the file ''newb.txt' file that we created just a
                    few minutes ago. This code will do the trick…

                    Private Sub Command1_Click()

                    Kill "c:vbfilesnewb.txt"

                    End Sub

                    Again, there will be no confirmation message, only an error message if the
                    file we are attempting to delete does not exist.




http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (6 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6




                    As I mentioned, you can also use wildcards as an argument to the Kill
                    statement (WARNING: Don’t attempt this at home!!!). For instance, this code
                    will delete EVERY file in the VBFILES directory that has a file extension of *.
                    txt…

                    Private Sub Command1_Click()

                    Kill "c:vbfiles*.txt"

                    End Sub

                    Most dangerously, this code will delete EVERY file in the VBFILES
                    directory…

                    Private Sub Command1_Click()

                    Kill "c:vbfiles*.*"

                    End Sub

                    Be careful when using the Kill statement---when issued through Visual Basic,
                    there's no going back. There is no Undo statement, and files deleted in this
                    way are NOT moved to the Windows Recycle bin.

                    Moving Files

                    There is no explicit Visual Basic statement to move a file. To simulate a move
                    of a file, all we need to do is combine the FileCopy and Kill statements that
                    we've already seen. For instance, to move the file a.txt from C:VBFILES to C:
                    VBILESCHINA, we can execute this code…


http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (7 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6



                    Private Sub Command1_Click()

                    FileCopy "c:vbfilesa.txt", "c:vbfileschinaa.txt"

                    Kill "c:vbfilesa.txt"

                    End Sub

                    Again, don't expect any confirmation messages---only errors if the files you
                    reference do not exist.

                    That's it for Visual Basic actions that we can take against files---now it's time
                    to turn our attention to Directory or folder operations.

                    Creating a Directory (Folder)

                    Creating a Folder is something that we're used to doing using Windows
                    Explorer, but Visual Basic gives us the capability of creating folders within our
                    program using the MkDir statement. Here's the syntax…

                    MkDir path

                    where path is either the name of a folder to be created, or (better yet!) the full
                    path name of the directory or folder that you wish to create.

                    Specifying just the folder name to be created can be dangerous---if you are
                    not aware of the current drive and directory, you may wind up creating a
                    folder somewhere on your hard drive, with no real idea where it went. Better
                    to be sure and specify the full path name, like this

                    Private Sub Command1_Click()

                    MkDir "c:vbfilessmiley"

                    End Sub

                    This code will create a folder called 'smiley' within the folder 'vbfiles' on the C
                    Drive. Once again, you'll receive no confirmation message if the folder is
                    created, but you will receive an error message if the folder creation fails.

                    There are two potential errors when executing the MkDir statement.



http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (8 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6

                    First, if you attempt to create a folder that already exists, you'll receive this
                    error message




                    The error message is not explicit enough for my liking, but that's what it
                    means---the folder 'smiley' already exists.

                    A second possible pitfall is attempting to create a folder within a folder that
                    itself does not exist. For instance, in this code

                    Private Sub Command1_Click()

                    MkDir "c:vbfilessmileyonetwo"

                    End Sub

                    if the folder 'one' does not yet exist within 'smiley', you can't create the folder
                    'two'--and you'll receive this error message…




http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (9 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6



                    Removing a Directory (Folder)

                    Removing a directory is similar to removing a file---in this case, we use the
                    Visual Basic RmDir statement. Here's the syntax…

                    RmDir path

                    As was the case with the MkDir statement, path can either be a file name or
                    the full path of a file name (once again, my recommendation). This code will
                    remove the folder 'smiley' that we just created …

                    Private Sub Command1_Click()

                    RmDir "c:vbfilessmiley"

                    End Sub

                    It should come as no surprise to you that there's no confirmation message
                    generated for a successful removal of the folder.

                    Possible error messages from RmDir?

                    There are two pitfalls. First, as we've seen all along, if you attempt to remove
                    a folder that does not exist, you'll receive this error message…




                    A second possible error can occur if you attempt to remove a directory or
                    folder that contains files. If you try, you'll receive this error message…




http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (10 of 11)3/28/2004 11:47:51 AM
File Operations in Visual Basic 6




                    You must first use the Kill statement to remove every file from the folder
                    before executing the RmDir statement (that's where the wildcard for the Kill
                    statement comes in handy!)

                    Moving a Directory (Folder)

                    As was the case with moving files, there is no explicit Visual Basic statement
                    that will do this for you.. To move a folder (and everything along with it), you'll
                    first need to create the new folder, then use FileCopy to copy all of its files to
                    the new folder, then delete all the files in the old folder using the Kill
                    statement, and finally remove the old folder.

                    Summary

                    The need to work with directories (folders) and files can arise during your
                    Visual Basic programming career---I hope this overview of the Visual Basic
                    file and folder statements will help you.

                    As I mentioned at the beginning of the article, the File System Object (FSO)
                    can also be used to do everything that you've seen here--but it's available
                    only in Visual Basic 6, and it requires a comfort level with Objects and
                    Collections that you may not yet have.

                    If there's a demand for it, I'll be glad to address it in an upcoming article.




http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (11 of 11)3/28/2004 11:47:51 AM

More Related Content

What's hot

Basic Linux day 2
Basic Linux day 2Basic Linux day 2
Basic Linux day 2
Saikumar Daram
 
Basic linux day 4
Basic linux day 4Basic linux day 4
Basic linux day 4
Saikumar Daram
 
Basic Linux day 6
Basic Linux day 6Basic Linux day 6
Basic Linux day 6
Saikumar Daram
 
Linux command for beginners
Linux command for beginnersLinux command for beginners
Linux command for beginners
SuKyeong Jang
 
Unix Basics For Testers
Unix Basics For TestersUnix Basics For Testers
Unix Basics For Testers
nitin lakhanpal
 
Productivity tips - Introduction to linux for bioinformatics
Productivity tips - Introduction to linux for bioinformaticsProductivity tips - Introduction to linux for bioinformatics
Productivity tips - Introduction to linux for bioinformatics
BITS
 
Basic command ppt
Basic command pptBasic command ppt
Basic command ppt
Rohit Kumar
 
Linux class 8 tar
Linux class 8   tar  Linux class 8   tar
BASIC COMMANDS OF LINUX
BASIC COMMANDS OF LINUXBASIC COMMANDS OF LINUX
Basic 50 linus command
Basic 50 linus commandBasic 50 linus command
Basic 50 linus command
MAGNA COLLEGE OF ENGINEERING
 
Basic linux commands
Basic linux commandsBasic linux commands
Basic linux commands
Shakeel Shafiq
 
Linux Administrator - The Linux Course on Eduonix
Linux Administrator - The Linux Course on EduonixLinux Administrator - The Linux Course on Eduonix
Linux Administrator - The Linux Course on Eduonix
Paddy Lock
 
50 most frequently used unix linux commands (with examples)
50 most frequently used unix   linux commands (with examples)50 most frequently used unix   linux commands (with examples)
50 most frequently used unix linux commands (with examples)
Rodrigo Maia
 
OpenGurukul : Operating System : Linux
OpenGurukul : Operating System : LinuxOpenGurukul : Operating System : Linux
OpenGurukul : Operating System : Linux
Open Gurukul
 
Unix commands in etl testing
Unix commands in etl testingUnix commands in etl testing
Unix commands in etl testing
Garuda Trainings
 
Linux final exam
Linux final examLinux final exam
Linux final exam
Andrew Ibrahim
 
Linux basic commands
Linux basic commandsLinux basic commands
Linux basic commands
Sagar Kumar
 
Unix(introduction)
Unix(introduction)Unix(introduction)
Unix(introduction)
meashi
 
Text mining on the command line - Introduction to linux for bioinformatics
Text mining on the command line - Introduction to linux for bioinformaticsText mining on the command line - Introduction to linux for bioinformatics
Text mining on the command line - Introduction to linux for bioinformatics
BITS
 
Command-Line 101
Command-Line 101Command-Line 101
Command-Line 101
Artefactual Systems - AtoM
 

What's hot (20)

Basic Linux day 2
Basic Linux day 2Basic Linux day 2
Basic Linux day 2
 
Basic linux day 4
Basic linux day 4Basic linux day 4
Basic linux day 4
 
Basic Linux day 6
Basic Linux day 6Basic Linux day 6
Basic Linux day 6
 
Linux command for beginners
Linux command for beginnersLinux command for beginners
Linux command for beginners
 
Unix Basics For Testers
Unix Basics For TestersUnix Basics For Testers
Unix Basics For Testers
 
Productivity tips - Introduction to linux for bioinformatics
Productivity tips - Introduction to linux for bioinformaticsProductivity tips - Introduction to linux for bioinformatics
Productivity tips - Introduction to linux for bioinformatics
 
Basic command ppt
Basic command pptBasic command ppt
Basic command ppt
 
Linux class 8 tar
Linux class 8   tar  Linux class 8   tar
Linux class 8 tar
 
BASIC COMMANDS OF LINUX
BASIC COMMANDS OF LINUXBASIC COMMANDS OF LINUX
BASIC COMMANDS OF LINUX
 
Basic 50 linus command
Basic 50 linus commandBasic 50 linus command
Basic 50 linus command
 
Basic linux commands
Basic linux commandsBasic linux commands
Basic linux commands
 
Linux Administrator - The Linux Course on Eduonix
Linux Administrator - The Linux Course on EduonixLinux Administrator - The Linux Course on Eduonix
Linux Administrator - The Linux Course on Eduonix
 
50 most frequently used unix linux commands (with examples)
50 most frequently used unix   linux commands (with examples)50 most frequently used unix   linux commands (with examples)
50 most frequently used unix linux commands (with examples)
 
OpenGurukul : Operating System : Linux
OpenGurukul : Operating System : LinuxOpenGurukul : Operating System : Linux
OpenGurukul : Operating System : Linux
 
Unix commands in etl testing
Unix commands in etl testingUnix commands in etl testing
Unix commands in etl testing
 
Linux final exam
Linux final examLinux final exam
Linux final exam
 
Linux basic commands
Linux basic commandsLinux basic commands
Linux basic commands
 
Unix(introduction)
Unix(introduction)Unix(introduction)
Unix(introduction)
 
Text mining on the command line - Introduction to linux for bioinformatics
Text mining on the command line - Introduction to linux for bioinformaticsText mining on the command line - Introduction to linux for bioinformatics
Text mining on the command line - Introduction to linux for bioinformatics
 
Command-Line 101
Command-Line 101Command-Line 101
Command-Line 101
 

Viewers also liked

Tomatsu Seminar Presentation 110920
Tomatsu Seminar Presentation 110920Tomatsu Seminar Presentation 110920
Tomatsu Seminar Presentation 110920
Chika Watanabe
 
Task killer
Task killerTask killer
Task killer
ashpak
 
Bahas Istisyrak
Bahas IstisyrakBahas Istisyrak
Bahas Istisyrak
Asyraf Baharuddin
 
Maroon, anchorage
Maroon, anchorageMaroon, anchorage
Maroon, anchorage
Samox2
 
動画の作り方から稼ぎ方まで20130720
動画の作り方から稼ぎ方まで20130720動画の作り方から稼ぎ方まで20130720
動画の作り方から稼ぎ方まで20130720Keiko Morita
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
Barry Feldman
 

Viewers also liked (6)

Tomatsu Seminar Presentation 110920
Tomatsu Seminar Presentation 110920Tomatsu Seminar Presentation 110920
Tomatsu Seminar Presentation 110920
 
Task killer
Task killerTask killer
Task killer
 
Bahas Istisyrak
Bahas IstisyrakBahas Istisyrak
Bahas Istisyrak
 
Maroon, anchorage
Maroon, anchorageMaroon, anchorage
Maroon, anchorage
 
動画の作り方から稼ぎ方まで20130720
動画の作り方から稼ぎ方まで20130720動画の作り方から稼ぎ方まで20130720
動画の作り方から稼ぎ方まで20130720
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
 

Similar to Smiley011

Chapter10
Chapter10Chapter10
Chapter10
vishalw24
 
Command Line Tools
Command Line ToolsCommand Line Tools
Command Line Tools
David Harris
 
There are 4 parts for the project. The question may be long to r.docx
There are 4 parts for the project. The question may be long to r.docxThere are 4 parts for the project. The question may be long to r.docx
There are 4 parts for the project. The question may be long to r.docx
susannr
 
There are 4 part for the project and the question may be long to rea.docx
There are 4 part for the project and the question may be long to rea.docxThere are 4 part for the project and the question may be long to rea.docx
There are 4 part for the project and the question may be long to rea.docx
susannr
 
There are 4 parts for the project. The question may be long to read .docx
There are 4 parts for the project. The question may be long to read .docxThere are 4 parts for the project. The question may be long to read .docx
There are 4 parts for the project. The question may be long to read .docx
susannr
 
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
Sam Kim
 
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS: Introduction to Linux - Text manipulation tools for bioinformaticsBITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS
 
Vista Forensics
Vista ForensicsVista Forensics
Vista Forensics
CTIN
 
History
HistoryHistory
Root file system for embedded systems
Root file system for embedded systemsRoot file system for embedded systems
Root file system for embedded systems
alok pal
 
Managing files chapter 7
Managing files chapter 7 Managing files chapter 7
Managing files chapter 7
shinigami-99
 
Managing files chapter 7
Managing files chapter 7 Managing files chapter 7
Managing files chapter 7
shinigami-99
 
Updates
UpdatesUpdates
Updates
UpdatesUpdates
Automate the boring stuff with python
Automate the boring stuff with pythonAutomate the boring stuff with python
Automate the boring stuff with python
DEEPAKSINGHBIST1
 
Managing your data - Introduction to Linux for bioinformatics
Managing your data - Introduction to Linux for bioinformaticsManaging your data - Introduction to Linux for bioinformatics
Managing your data - Introduction to Linux for bioinformatics
BITS
 
My History
My HistoryMy History
My History
santosh mishra
 
Win98 System File Details
Win98 System File DetailsWin98 System File Details
Win98 System File Details
Sais Abdelkrim
 
Problem How do you copy a file Analyze the problem and con.pdf
Problem How do you copy a file Analyze the problem and con.pdfProblem How do you copy a file Analyze the problem and con.pdf
Problem How do you copy a file Analyze the problem and con.pdf
aadeshwarexports
 
Please answer all parts of the following question thoroughly.This .pdf
Please answer all parts of the following question thoroughly.This .pdfPlease answer all parts of the following question thoroughly.This .pdf
Please answer all parts of the following question thoroughly.This .pdf
amayagency123
 

Similar to Smiley011 (20)

Chapter10
Chapter10Chapter10
Chapter10
 
Command Line Tools
Command Line ToolsCommand Line Tools
Command Line Tools
 
There are 4 parts for the project. The question may be long to r.docx
There are 4 parts for the project. The question may be long to r.docxThere are 4 parts for the project. The question may be long to r.docx
There are 4 parts for the project. The question may be long to r.docx
 
There are 4 part for the project and the question may be long to rea.docx
There are 4 part for the project and the question may be long to rea.docxThere are 4 part for the project and the question may be long to rea.docx
There are 4 part for the project and the question may be long to rea.docx
 
There are 4 parts for the project. The question may be long to read .docx
There are 4 parts for the project. The question may be long to read .docxThere are 4 parts for the project. The question may be long to read .docx
There are 4 parts for the project. The question may be long to read .docx
 
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
 
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS: Introduction to Linux - Text manipulation tools for bioinformaticsBITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
 
Vista Forensics
Vista ForensicsVista Forensics
Vista Forensics
 
History
HistoryHistory
History
 
Root file system for embedded systems
Root file system for embedded systemsRoot file system for embedded systems
Root file system for embedded systems
 
Managing files chapter 7
Managing files chapter 7 Managing files chapter 7
Managing files chapter 7
 
Managing files chapter 7
Managing files chapter 7 Managing files chapter 7
Managing files chapter 7
 
Updates
UpdatesUpdates
Updates
 
Updates
UpdatesUpdates
Updates
 
Automate the boring stuff with python
Automate the boring stuff with pythonAutomate the boring stuff with python
Automate the boring stuff with python
 
Managing your data - Introduction to Linux for bioinformatics
Managing your data - Introduction to Linux for bioinformaticsManaging your data - Introduction to Linux for bioinformatics
Managing your data - Introduction to Linux for bioinformatics
 
My History
My HistoryMy History
My History
 
Win98 System File Details
Win98 System File DetailsWin98 System File Details
Win98 System File Details
 
Problem How do you copy a file Analyze the problem and con.pdf
Problem How do you copy a file Analyze the problem and con.pdfProblem How do you copy a file Analyze the problem and con.pdf
Problem How do you copy a file Analyze the problem and con.pdf
 
Please answer all parts of the following question thoroughly.This .pdf
Please answer all parts of the following question thoroughly.This .pdfPlease answer all parts of the following question thoroughly.This .pdf
Please answer all parts of the following question thoroughly.This .pdf
 

Recently uploaded

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 

Recently uploaded (20)

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 

Smiley011

  • 1. File Operations in Visual Basic 6 File Operations in Visual Basic 6 I'm frequently asked how to perform file operations in Visual Basic--for instance, how to delete a file or create a directory or folder. In this month's article, I'm going to show you five basic file type operations using built in Visual Basic functions. These techniques are considered old style by programmers familiar with Object Oriented programming who prefer to use the File System Object (FSO). But a discussion of the F SO requires a knowledge of Objects and Collections---perhaps I'll discuss FSO in a future article, provided you promise to read my Objects book, Learn to Program Objects with Visual Basic 6. But back to File Operations using the built in Visual Basic functions to which I alluded. We can categorize these operations in two ways: operations on files and operations on directories, or the newer term, folders. Copying Files When you copy a file you keep the existing file, and make a copy of the file with a new name. Visual Basic provides a statement for this called FileCopy. Here's the syntax for the FileCopy statement FileCopy source, destination where source is the name of the file to copy, and destination is the name of the copied file. You have several choices when it comes to specifying the file names here--- you can use the full path names for the files, or you can just specify the name of the files. By way of background, Windows keeps track of something called the current drive and the current directory for us---these are basically pointers in the File System, and in the old days of DOS allowed us to perform mundane file operations without having to specify the name of the Drive and the Directory. These pointers still carry on in VB and Windows, so if we use this syntax in the Click Event Procedure of a Command Button Private Sub Command1_Click() FileCopy "a.txt", "b.txt" http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (1 of 11)3/28/2004 11:47:51 AM
  • 2. File Operations in Visual Basic 6 End Sub Windows looks for a file called "a.txt" in the current drive and current directory of our PC, and if the operating system finds it, copies the file as "b.txt", again in the default drive and directory of the PC. The problem here is that if the file is not found, your program bombs, just like this… The Current Drive and Current Directory As it turns out, Visual Basic has a function that can be used to determine the current directory called the CurDir function … Private Sub Command2_Click() MsgBox "The current directory is " & CurDir End Sub Changing the Current Drive and Current Directory http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (2 of 11)3/28/2004 11:47:51 AM
  • 3. File Operations in Visual Basic 6 Once you know the current directory, you can then use the ChDir and ChDrive functions to change either the current drive or the current directory, like this… Private Sub Command3_Click() ChDrive ("d") ChDir "vbfiles" MsgBox "The current directory is " & CurDir End Sub Now if you are like me, you may not want to leave anything to chance, in which case, you can use the full path name with the FileCopy statement, like this… Private Sub Command1_Click() FileCopy "c:vbfilesa.txt", "c:vbfilesb.txt" End Sub I should mention that here that if you attempt to copy a file that is opened, you'll receive this error message… http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (3 of 11)3/28/2004 11:47:51 AM
  • 4. File Operations in Visual Basic 6 Does a file exist? There's no confirmation that the copy was successful, but you can determine if a file exists by using the Visual Basic Dir$ function. The Dir$ function requires just a single argument representing the file name (as was the case with the CopyFile statement, you can specify just the file name or the full path name). If the file is found, then Dir$ returns the file name (not the full path). If the file is not found, then Dir$ returns an empty string. Let's see how we can use the Dir$ function to determine if a file exists before we copy it. Private Sub Command1_Click() Dim retval As String retval = Dir$("c:vbfilesb.txt") If retval = "b.txt" Then MsgBox "b.txt exists--no need to copy it..." Else FileCopy "c:vbfilesa.txt", "c:vbfilesb.txt" End If End Sub If we now run the program, and click on the command button… http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (4 of 11)3/28/2004 11:47:51 AM
  • 5. File Operations in Visual Basic 6 We receive a message saying that the file already exists---Dir$ has done its job. By the way, you'll discover that there's a Dir function as well---Dir returns a variant return value and Dir$ returns a string. Renaming Files Renaming files is similar to copying them--this time we use the Visual Basic Name statement. Here's the syntax. Name oldpathname As newpathname As was the case when we copied files, we can choose either to specify a file name or to include the full path name---once again, I advise the full path name… Private Sub Command1_Click() Name "c:vbfilesb.txt" As "c:vbfilesnewb.txt" End Sub This code will result in the file 'b.txt' begin renamed to 'newb.txt'. Once again, don't expect a confirmation message telling you that the rename was successful--the only message you'll receive is if the file does not exist http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (5 of 11)3/28/2004 11:47:51 AM
  • 6. File Operations in Visual Basic 6 Deleting Files The final file operation I'll discuss in this article is that of deleting a file. Visual Basic provides us with the Kill statement which will delete a file (and dangerously, a wildcard selection of files) of our choosing. Here's the syntax… Kill pathname Let's say that we wish to delete the file ''newb.txt' file that we created just a few minutes ago. This code will do the trick… Private Sub Command1_Click() Kill "c:vbfilesnewb.txt" End Sub Again, there will be no confirmation message, only an error message if the file we are attempting to delete does not exist. http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (6 of 11)3/28/2004 11:47:51 AM
  • 7. File Operations in Visual Basic 6 As I mentioned, you can also use wildcards as an argument to the Kill statement (WARNING: Don’t attempt this at home!!!). For instance, this code will delete EVERY file in the VBFILES directory that has a file extension of *. txt… Private Sub Command1_Click() Kill "c:vbfiles*.txt" End Sub Most dangerously, this code will delete EVERY file in the VBFILES directory… Private Sub Command1_Click() Kill "c:vbfiles*.*" End Sub Be careful when using the Kill statement---when issued through Visual Basic, there's no going back. There is no Undo statement, and files deleted in this way are NOT moved to the Windows Recycle bin. Moving Files There is no explicit Visual Basic statement to move a file. To simulate a move of a file, all we need to do is combine the FileCopy and Kill statements that we've already seen. For instance, to move the file a.txt from C:VBFILES to C: VBILESCHINA, we can execute this code… http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (7 of 11)3/28/2004 11:47:51 AM
  • 8. File Operations in Visual Basic 6 Private Sub Command1_Click() FileCopy "c:vbfilesa.txt", "c:vbfileschinaa.txt" Kill "c:vbfilesa.txt" End Sub Again, don't expect any confirmation messages---only errors if the files you reference do not exist. That's it for Visual Basic actions that we can take against files---now it's time to turn our attention to Directory or folder operations. Creating a Directory (Folder) Creating a Folder is something that we're used to doing using Windows Explorer, but Visual Basic gives us the capability of creating folders within our program using the MkDir statement. Here's the syntax… MkDir path where path is either the name of a folder to be created, or (better yet!) the full path name of the directory or folder that you wish to create. Specifying just the folder name to be created can be dangerous---if you are not aware of the current drive and directory, you may wind up creating a folder somewhere on your hard drive, with no real idea where it went. Better to be sure and specify the full path name, like this Private Sub Command1_Click() MkDir "c:vbfilessmiley" End Sub This code will create a folder called 'smiley' within the folder 'vbfiles' on the C Drive. Once again, you'll receive no confirmation message if the folder is created, but you will receive an error message if the folder creation fails. There are two potential errors when executing the MkDir statement. http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (8 of 11)3/28/2004 11:47:51 AM
  • 9. File Operations in Visual Basic 6 First, if you attempt to create a folder that already exists, you'll receive this error message The error message is not explicit enough for my liking, but that's what it means---the folder 'smiley' already exists. A second possible pitfall is attempting to create a folder within a folder that itself does not exist. For instance, in this code Private Sub Command1_Click() MkDir "c:vbfilessmileyonetwo" End Sub if the folder 'one' does not yet exist within 'smiley', you can't create the folder 'two'--and you'll receive this error message… http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (9 of 11)3/28/2004 11:47:51 AM
  • 10. File Operations in Visual Basic 6 Removing a Directory (Folder) Removing a directory is similar to removing a file---in this case, we use the Visual Basic RmDir statement. Here's the syntax… RmDir path As was the case with the MkDir statement, path can either be a file name or the full path of a file name (once again, my recommendation). This code will remove the folder 'smiley' that we just created … Private Sub Command1_Click() RmDir "c:vbfilessmiley" End Sub It should come as no surprise to you that there's no confirmation message generated for a successful removal of the folder. Possible error messages from RmDir? There are two pitfalls. First, as we've seen all along, if you attempt to remove a folder that does not exist, you'll receive this error message… A second possible error can occur if you attempt to remove a directory or folder that contains files. If you try, you'll receive this error message… http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (10 of 11)3/28/2004 11:47:51 AM
  • 11. File Operations in Visual Basic 6 You must first use the Kill statement to remove every file from the folder before executing the RmDir statement (that's where the wildcard for the Kill statement comes in handy!) Moving a Directory (Folder) As was the case with moving files, there is no explicit Visual Basic statement that will do this for you.. To move a folder (and everything along with it), you'll first need to create the new folder, then use FileCopy to copy all of its files to the new folder, then delete all the files in the old folder using the Kill statement, and finally remove the old folder. Summary The need to work with directories (folders) and files can arise during your Visual Basic programming career---I hope this overview of the Visual Basic file and folder statements will help you. As I mentioned at the beginning of the article, the File System Object (FSO) can also be used to do everything that you've seen here--but it's available only in Visual Basic 6, and it requires a comfort level with Objects and Collections that you may not yet have. If there's a demand for it, I'll be glad to address it in an upcoming article. http://www.johnsmiley.com/cis18.notfree/Smiley011/Smiley011.htm (11 of 11)3/28/2004 11:47:51 AM