C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Working With Directories and Files


Posted Date: 10 Mar 2004    Resource Type: Articles    Category: .NET Framework
Author: ManojRajanMember Level: Gold    
Rating: Points: 10



Working With Files And Directories


The System.IO namespace provides a set of classes for accessing and managing files and directories. Using this namespace you can read and write information about the directories and files. In fact this namespace is more than a file system object, ie, it can work with any type of storage using stream objects. For all the examples specified below, you must import the namespace above the class declaration.

Imports System.IO


Managing Directories

There are two classes available for managing the directories.

1.Directory
This class is a collection of static methods to manage end retrieve information about a directory.

2.DirectoryInfo
This class exposes instance methods for creating, moving, and enumerating through directories and subdirectories..


Directory Class

1. CreateDirectory

This method is for creating all directories specified by the Path argument, the directory name along with the path info. All directories specified in the path that does not exist will be created.

e.g .
Dim temp As IO.Directory
temp.CreateDirectory("C:\New\New\new\new1")

2.Delete

This method is an overloaded method. The first one accepts a single argument, path of the directory. The directory to be removed must be writable or empty. The path argument can be a relative or full path of the directory. The second one accepts two arguments, one is the fully qualified name of the directory to be removed and the second one a Boolean argument (True: to remove all sub directories and files).

e.g.
Dim temp As IO.Directory
temp.Delete("C:\New\New\new\new1")

OR

temp.Delete("C:\New", True)


3.Exists

This method is to check whether the directory specified exists or not. It accepts a single argument, the path of the directory.

e.g.

Dim temp As IO.Directory
If temp.Exists("C:\New\New\new\new1") then
ProcessDirectory()
End if


4.GetCreationTime

This method accepts a single argument, the path of the directory and returns the Creation time (Date and time).

e.g.

Dim temp As IO.Directory
Label2.Text = temp.GetCreationTime("C:\New\New\new\new1")

5.GetCurrentDirectory

This method returns the path of the current working directory, can be used in conjunction with the Delete and create methods to specify a relative path.

e.g.

Dim temp As IO.Directory
Label2.Text = temp. GetCurrentDirectory()

6.GetDirectories

This is an overloaded method. One returns a string array of sub directories in the specified Path. And the second one accepts two arguments one the path and the other the search pattern (The search pattern includes partial names with wildcard characters *and?), returns a string array of sub directories matching the search pattern.



e.g.

Dim temp as IO.Directory
Dim subdir As String() = temp.GetDirectories(“C:\New”)

Dim subdirectory As String
For Each subdirectory In subdir
ProcessDirectory(subdirectory)
Next

OR



Dim temp as IO.Directory
Dim subdir As String() = temp.GetDirectories(“C:\New”,”N?w*”)

Dim subdirectory As String
For Each subdirectory In subdir
ProcessDirectory(subdirectory)
Next


7.GetDirectoryRoot

This method accepts a Path argument and returns the root information.

Dim temp As IO.Directory
Label2.Text = temp.GetDirectoryRoot("C:\New\New\new\new1\Test1")

8. GetFiles

Overloaded method. Same as GetDirectories but returns a string array containing the files in the specified path.

9. GetFileSystemEntries

Overloaded method. Same as GetDirectories but returns a string array of sub directories and files.

10. GetLastAccessTime

This method returns the last access time of the file or directory as specified in the path.

e.g.

Dim temp As IO.Directory
Label2.Text = temp.GetLastAccessTime("c:\new\test.txt")

11.GetLastWriteTime

This method returns the date and time of the specified file or directory was last written to.

12.GetLogicalDrives

This method retrieves the names (string array) of the logical drives on this computer in the form ":\".

e.g.

Dim temp As IO.Directory
Dim str As String
For Each str In temp.GetLogicalDrives()
Label2.Text = Label2.Text & “ “ & str
Next


13.GetParent

This method retrieves the parent directory of the specified path, including both absolute and relative paths. You can use this returned object to manipulate the Parent directory.


14.Move

This method move a file or a directory and its contents to a new location in same volume. Accepts two arguments, first is the source, second is the destination path.

e.g.

Dim temp As IO.Directory
temp.Move("C:\new", "c:\Old")

15.SetCreationTime

This method sets the creation date and time for the specified file or directory.

e.g.

Dim temp As IO.Directory
temp.SetCreationTime("c:\Test", "1/31/04 10:10:10 PM")

16.SetCurrentDirectory

This method sets the application's current working directory to the specified directory.

e.g.
Dim temp As IO.Directory
Label2.Text = temp.GetCurrentDirectory()
temp.SetCurrentDirectory("C:\Test")
Label2.Text = Label2.Text & " " & temp.GetCurrentDirectory

17.SetLastAccessTime

Sets the last access time of a file or directory.

18SetLastWriteTime

Sets the last write time of a file or directory.



Managing Files

The File Class provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

1.AppendText

This method creates a StreamWriter that appends UTF-8 encoded text to an existing file.

e.g.

Dim temp As File
Dim Str As TextWriter = temp.AppendText("c:\Test.txt")
Str.WriteLine("This is created by")
Str.WriteLine("ManojRajan")
Str.WriteLine("For texting")
Str.Close()

If Test.txt does not exist, it will create the file.


2.Copy

This method is overloaded, one copies an existing file to a new file, accepting two arguments, the source and the destination. Overwriting a file of the same name is not allowed. The second one accepts three arguments, the source, the destination and a Boolean argument to overwrite if the destination file already exists.

e.g.

Dim temp As File
temp.Copy("c:\Test.txt", "C:\Test2.txt")
OR
Dim temp As File
temp.Copy("c:\Test.txt", "C:\Test2.txt", True)

3.Create

This method is overloaded, one method creates a file in the specified fully qualified path by accepting a single argument, the file path and returns a FileStream that provides read/write access to the specified file, If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten. And the second one creates or overwrites the specified file by accepting two arguments, the file path and the bufferSize (The number of bytes buffered for reads and writes to the file).

e.g.
Dim temp As File
Dim Str As FileStream = temp.Create("c:\Test.txt")
Dim stm As New StreamWriter(Str)
stm.WriteLine("This is the First Line”)
stm.WriteLine("This is the seconf Line")
stm.Close()
Str.Close()

4.CreateText

Creates or opens a new file for writing UTF-8 encoded text. Returns a stream writer. If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.

e.g.

Dim temp As File
Dim Str As StreamWriter = temp.CreateText("c:\Test.txt")
Str.WriteLine("This is the First Line ")
Str.WriteLine("This is the second line")
Str.Close()

5.Delete

Deletes the file specified by the fully qualified path by accepting a single argument, the file path. If the file does not exist an exception will be raised.

6.Exists

This method is to check whether the file specified exists or not. It accepts a single argument, the path of the directory. Returns a Boolean true if the file exists else return False.

7. .GetCreationTime

This method accepts a single argument, the path of the file and returns the Creation time (Date and time).

e.g.

Dim temp As File
Label2.Text = temp.GetCreationTime("C:\test.txt")


8.GetLastAccessTime

This method returns the last access time of the file as specified in the path.

e.g.
Dim temp As file
Label2.Text = temp.GetLastAccessTime("c:\test.txt")

9. GetLastWriteTime

This method returns the date and time of the specified file.

10.Move

This method moves a specified file to a new location, providing the option to specify a new file name. Accepts two arguments, the source and the destination.

11.Open

This is an overloaded method,

1.Opens a FileStream on the specified path with read/write access. Accepts two arguments, the file path and the file mode. Returns a FileStream with the specified mode.

FilesModes


Append
Opens the file if it exists and seeks to the end of the file, or creates a new file. FileMode.Append can only be used in conjunction with FileAccess.Write.

Create
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten.

CreateNew
Specifies that the operating system should create a new file.

Open
Specifies that the operating system should open an existing file.

OpenorCreate
Specifies that the operating system should open a file if it exists; otherwise, a new file should be created.

Truncate
Specifies that the operating system should open an existing file. Once opened, the file should be truncated so that its size is zero bytes.

2.Opens a FileStream on the specified fully qualified path, with the specified mode and access. Returns a FileStream with the specified mode and access.

FileAccess


Read
Read access to the file. Data can be read from the file.

ReadWrite
Read access to the file. Data can be read from the file.

Write
Write access to the file. Data can be written to the file.

3. Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.
Accepts four arguments file path, mode, access and the share type.






Responses

Author: Rick Binns    17 Aug 2004Member Level: Bronze   Points : 0
very simple explanation of the pieces needed for directory manipulation. Uses a simple direct approach that any programmer should be able to understand


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Creating multiline tooltips
Previous Resource: Solving the "Could not copy temporary files to the output directory" error
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design


Contact Us    Privacy Policy    Terms Of Use