File I/O
Microsoft .NET framework provides the most efficient types to work
with input and output operations. In this article we will learn how to use
those built in types and their methods to perform our tasks. Initially we begin
with reading and writing file streams.
Reading and Writing Files:
Many times as a developer we need to work with reading and writing
the files. The .NET framework makes it easy to perform these tasks.
Stream Class:
Stream class is the base class for all type of stream class available in
System.IO namespace. By learning how to work with a stream in general, you can
apply that knowledge to any type of stream. The different types of streams
available are:
- FileStream.
- MemoryStream
.
Before we go through the FileStream class we will have a close
look at the File and Direcorty classes.
The File Class:
The File Class provides numerous static methods to work with
files. Some of the common methods used with File class are as follows.
By using the file class one can perform the following operations.
- Create a
file:- To create a new file.
File.Create("D:\\hello.txt");
- Move a
file:- To move a file from one location to another location.
File.Move("D:\\hello.txt", "C:\\hello.txt");
- Copy a
file:- To copy a file.
File.Copy("D:\\hello.txt", "C:\\hello.txt");
- Open a
file:- To open a file for reading.
File.OpenRead("D:\\hello.txt");
- WriteAllBytes:-
To write binary data to file.
byte[] data = new byte[3] {
0,0,1};
File.WriteAllBytes("D:\\hello.txt",data);
- WriteAllText:-
To write text to the file.
File.WriteAllText("D:\\hello.txt", "This
is teh first line");
- ReadAllBytes:-
To read binary data from file.
File.ReadAllBytes("D:\\hello.txt");
- ReadAllText:-
To read text from file.
File.ReadAllText("D:\\hello.txt");
- Delete a
file:- To delete a file.
File.Delete("D:\\hello.txt");
- Exists:- To
determine whether the specified file exists.
File.Exists("D:\\hello.txt");
The Directory Class:
The Directory Class has numerous
static methods which allow us to work with directories. The most common methods
used with this type are as follows:
- Create a directory: - To create a new directory.
Directory.CreateDirectory("D:\New Folder");
- Delete a directory: - To delete a directory.
Directory.Delete("D:\\New Folder");
- Exists: - Determine whether specified path refers to an existing directory.
Directory.Exists("D:\\New
Folder");
- Move a file: - To move a directory from one location to another location.
Directory.Move("D:\\New Folder",
"F:\\New Folder");
- Copy a file: - To copy a file from one directory to another directory.
Directory.Move("D:\\New
Folder", "F:\\New Folder");
- Get Directories: - To get the subdirectories in a directory.
Directory.GetDirectories("D:\\New
Folder");
- Get Files: - To get the files in a directory.
Directory.GetFiles("D:\\New
Folder");
- GetCreationTime: - To get the creation time of the directory.
Directory.GetCreationTime("D:\\New
Folder");
No comments:
Post a Comment