working with files and folders

Upload: raghavendra-katti

Post on 03-Jun-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Working With Files and Folders

    1/7

    Working with Files and Folders

    - OS uses basic units of data storage as File and Directory.- Fileis structure or container storing related data.- Directoryis location where file or files are stored.- VB.NET programming as like other programming language supports use of File and Directory for

    its data storage.

    - Files in program are used either to get input, give output or for both.- To perform these file handling operations, VB.Net support different built-in classes like- File- Directory- Path- FileInfo- DirectoryInfo

    The File Class

    The File class provides the .NET Framework's support for all manner of file handling. With this class,

    you can create, copy, delete, move, and open files and much more.File is a static or shared "operations" class and not a class for objects. You cannot instantiate File and ithas no constructor. To use File, simply reference it asfollows:

    Directory Class

    - It is the member of System.IO namespace / package.- It contains all the static methods for all directory or folder operations.- This class can not be inherited.- It supports following functions:

    i. CreateDirectory(DirName) It creates directory in by given name in given path.Directory.CreateDirectory(C:\tmp\dir1)

    ii. Exists(DirName)it checks the given directory in given location and returns TRUE if itis present else returns FALSE

    Directory.Exists(C:\tmp\dir1)

    iii. GetDirectories(DirName) - It returns the list of all the directories present in the givendirectory

    Directory.GetDirectories(c:\tmp\dir1)

    iv. GetFiles(Dirname)It returns the list of all the files present in the given directory.Directory.GetFiles(c:\tmp\dir1)

    v. GetDirectoryRoot(DirName)It returns the name of Root Directory of the givendirectory.

    Directory.GetDirectoryRoot(c:\tmp\dir1)

    vi. GetParent(DirName)It returns the name of the parent Directory of the givendirectory.

    Directory.GetParent(c:\tmp\dir1)

    vii. Move(SourceLoc,DestLoc)Moves the directory from source location to destinationlocation along with its all contents.

    Directory.Move(c:\tmp\dir1,d:\dir1)

    viii. Delete(DirName) it removes the directory and all its contents.Directory.Delete(c:\tmp\dir1)

  • 8/12/2019 Working With Files and Folders

    2/7

    FileInfo

    - It is the member of System.IO namespace.- It provides all the instance methods to perform all the file related operations.- As like function, also having build-in properties.- To instantiate the FileInfo class as:- Dim as new FileInfo(filename)- Dim f as new FileInfo(C:\tmp\a1.txt)

    Properties

    i. Directorythis property is used to return the name of parent directory in which file ispresent.

    Msgbox (f.Directory)

    ii. DirectoryNameit returns the full path from root directory to file nameMsgbox (f.DirectoryName)

    iii. ExistsIt returns TRUE if file already present else returns FALSEMsgbox (f.Exists)

    iv. IsReadOnly - It returns TRUE if file already present else returns FALSEMsgbox (f.IsReadOnly)

    v. Lengthit returns the length i.e. total no of character i.e. size as integerMsgbox (f.Length)

    Methods

    i. Create()to create new file by the given namef.create()

    ii. MoveTo(DestinationLoc) moves the file to the given destination.f.moveTo(D:\abc)

    iii. Copyto(Destination) copes the file to the given destination by given namef.CopyTo(C:\abc\a5.txt)

    iv. Delete()Deletes the file along with its contentsf.Delete()

    DirectoryInfo

    - It is the member of System.IO namespace.- It provides all the instance methods to perform all the Directory / Folder related operations.- As like function, also having build-in properties.- To instantiate the DirectoryInfo class as:- Dim as new DirectoryInfo(Dirname)- Dim f as new DirectoryInfo(C:\tmp\)

    Properties

    i. ExistsIt returns TRUE if dir already present else returns FALSEMsgbox (f.Exists)

    ii. CreationTime - It returns date and time value of the given directory.Msgbox (f.CreationTime)

    iii. FullNameit returns the complete path and name of the given directory.Msgbox (f.FullName)

  • 8/12/2019 Working With Files and Folders

    3/7

    iv. Parent - It returns the name of parent directory of the given directory obj.Msgbox (f.Parent)

    v. Rootit returns the name of root directory of the given directory obj.Msgbox (f.Root)

    Methods

    v. Create()to create new directory by the given namef.create()

    ix. GetDirectories() - It returns the list of all the directories present in the given directoryf.GetDirectories()

    x. GetFiles(Dirname) It returns the list of all the files present in the given directory.f.GetFiles()

    vi.vii. Moveto(Destination) moves the directory and it contents to the given destination by

    given name

    f.MoveTo(d:\)

    viii. Delete()Deletes the directory and its all files .f.Delete()PathIt is the member of System.IO namespace.

    - Used as supporting class for other File and Directory System related classes.- It also provides built-in static methods

    i. ChangeExtension(path,ext)to change the extension of given path or file namePath.ChangeExtension(C:\a1.txt,c:\a1.dat)

    ii. GetDirectoryName(path)returns the name of directory for the given file.Path.GetDirectoryName(c:\tmp\a1.txt)

    iii. GetExtension(path)returns the current extension of given filePath.GetExtension(c:\a1.txt)

    iv. GetFullPath(path)returns the complete path of given file / directory starting fromroot directory including file name.

    Path.GetFullPath(C:\tmp\a1.txt)

    v. GetFileName(path) returns only the file nameFileStream

    - File Stream class used to read from, write to, open and to close file any location within a filesystem.

    - Stream class is used to read from and to write character from the text file.- As a class it is having built-in constructors and methods- Constructors

    o FileStream(FileName,Mode)FileNameis valid path and name of file to be used for input or output.

    Mode can be any one of following constants;

    - FileMode.Appendadd new contents by keeping old contents- FileMode.Createcreate new file- FileMode.Openopen the file if it is existing- FileMode.Truncateopen the file, and if it is existing , removes all its contents

  • 8/12/2019 Working With Files and Folders

    4/7

  • 8/12/2019 Working With Files and Folders

    5/7

    - When object is created by Using..End Using keyword, it is ensured that, after finishing the job,Vb.NET disposes the object and frees the resource.

    Using as new StreamReader(FilePathandName)

    End Using

    Using fobj as new StreamReader(C:\tmp\a1.txt)

    ---

    ---

    End Using

    Property

    i. EndOfStreamreturns TRUE or FALSE. If the reading position to the end of file stream itreturns true and reading can be stopped.

    Fobj.EndofStream

    Methods

    i. Read()is used to read a single character from the fileS=Fobj.Read()

    ii. ReadLine()is used to read a complete line from the file.S=Fobj.ReadLine()

    iii. ReadToEnd()is used to read whole contents of file.S=Fobj.ReadToEnd()

    iv. Close()is used to close the file stream and stop any further read action.Fobj.Close()

    v. Dispose()is used to close the file and also deallocates the resources.Fobj.Dispose()

    e.g.

    PrivateSubButton4_Click()Usingf AsNewStreamReader("C:\tmp\vbn.txt")

    TextBox1.Text = f.ReadToEnd()EndUsing

    EndSub

  • 8/12/2019 Working With Files and Folders

    6/7

    StreamWriter || Sending Data to File

    - This library class is a member of System.IO namespace.- It creates a textreader stream to write character data in given file.- Its object can be created in one of the following way:

    o With dim keywordWith dim keyword when an object is created for StreamWriter, it may not be automatically

    disposed and frees the resource. The object can be created as:

    Dim as new StreamWriter(FilePathAndName)

    Dim f as new StreamWriter(C:\tmp\a1.txt)

    o With Using End Using- When object is created by Using..End Using keyword, it is ensured that, after finishing the job,

    Vb.NET disposes the object and frees the resource.

    Using as new StreamWriter(FilePathandName)

    End Using

    Using fobj as new StreamWriter(C:\tmp\a1.txt)

    ---

    ---

    End Using

    Property

    i. AutoFlushis used to set the auto flush property TRUE or FALSE so that data from buffer can be

    pushed to file.

    Methods

    i. Write()is used to write a single character in the fileFobj.write(s)

    ii. ReadLine()is used to Write a complete line in the file.Fobj.ReadWrite(s)

    iii. Flush()is used to push the data from buffer to file.Fobj.Flush()

    iv. Close()is used to close the file stream and stop any further write action.Fobj.Close()

    v. Dispose()is used to close the file and also deallocates the resources.Fobj.Dispose()

    e.g.

    PrivateSubButton3_Click()Dimf AsNewStreamWriter("C:\tmp\vbn.txt")

    f.WriteLine("Hello and welcome")f.Flush()MsgBox("Ok")

    EndSub

  • 8/12/2019 Working With Files and Folders

    7/7

    FileSystemWatcher

    - The FileSystemWatcher is one of the control available on the std toolbox of VB.NET IDE.- It allows you to monitor file creations, deletions, errors, modified file and even file renames. The

    FileSystemWatcher allows you to set the Path to monitor, monitor certain extensions, and even

    set it up to monitor the subdirectories in the path you specified.

    - For this it needs supports of another control i.e. FileBrowserDialog- Add FileSystemWatcher and rename to FSW1- Add FileBrowserDialog and rename to FBD1- Change Root Folder=My Computer of FBD- and design the form as:

    PrivateSubButton1_Click(ByValsender AsSystem.Object, ByVale AsSystem.EventArgs) HandlesButton1.Click

    fbd1.ShowDialog()TextBox1.Text = fbd1.SelectedPathfsw1.Path = TextBox1.TextMsgBox("Path to monitor is now set to: "& TextBox1.Text)

    EndSubPrivateSubfsw1_Renamed(ByValsender AsObject, ByVale As

    System.IO.FileSystemEventArgs) HandlesFSW1.RenamedListBox1.Items.Add("File- "& e.FullPath.ToString & " renamed

    at: "& System.DateTime.Now)EndSubPrivateSubfsw1_Created(ByValsender AsObject, ByVale As

    System.IO.FileSystemEventArgs) HandlesFSW1.CreatedListBox2.Items.Add("File- "& e.FullPath.ToString & " created

    at: "& System.DateTime.Now)EndSubPrivateSubfsw1_Deleted(ByValsender AsObject, ByVale As

    System.IO.FileSystemEventArgs) HandlesFSW1.DeletedListBox3.Items.Add("File- "& e.FullPath.ToString & " deleted

    at: "& System.DateTime.Now)EndSubPrivateSubfsw1_Changed(ByValsender AsObject, ByVale As

    System.IO.FileSystemEventArgs) HandlesFSW1.ChangedListBox4.Items.Add("File- "& e.FullPath.ToString & " modified

    at: "& System.DateTime.Now)EndSub