General Instructions:: Programming 2 - Module 5
General Instructions:: Programming 2 - Module 5
GENERAL INSTRUCTIONS:
III. References
https://www.completecsharptutorial.com
https://www.msdotnet.co.in/2013
https://www.c-sharpcorner.com
http://csharp.net-informations.com
Lesson 1
Directory Class, File Class and File Stream Class
Objectives:
Learning outcome:
Student could:
a. create a C# program applying directory class or directory info class
b. create a C# program applying file class and file info class
d. create a C# program using filestream class
Getting and doing manipulation regarding Directory, you may use Directory and
DirectoryInfo Classes.
Wherein:
Directory Class Provide Static Method.
DirectoryInfo class provide Non Static Method.
Syntax
Note:
Before creating a directory or folder , check that directory or folder exist or not. In C#
use Exists method in the Directory class.
Syntax
To move a directory and its contents from one location to another, use the Move
method in the C# Directory class.
Syntax
When we want to delete a directory we can use the Delete method in the C# Directory
class.
Syntax
DirPath : The Directory we want to delete.
Step :2 Double click on Submit Button and write the following codes which is given
below:
using System;
using System.IO;
using System.Windows.Forms;
namespace Directory_class
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Description: Here i have entered Existing Directory(os) and click the submit button
,then sub directory under Directory(os) will be showed in the comboBox .
Example 2:
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
{
//create the directory testDir1
Directory.CreateDirectory("c:\\testDir1");
MessageBox.Show("testDir1 created ! ");
//create the directory testDir2
Directory.CreateDirectory("c:\\testDir1\\testDir2");
MessageBox.Show("testDir2 created ! ");
//move the directory testDir2 as testDir in c:\
Directory.Move("c:\\testDir1\\testDir2", "c:\\testDir");
MessageBox.Show("testDir2 moved ");
//delete the directory testDir1
Directory.Delete("c:\\testDir1");
MessageBox.Show("testDir1 deleted ");
}
}
}
}
DirectoryInfo class allows you to work with directory and its make directory
manipulation as create, delete, info etc easy. It exposes instance methods for creating,
moving, enumerating through directories and subdirectories.
Important Points:
Step :2 Double click on Submit Button and write the following codes which is given
below:
using System;
using System.IO;
using System.Windows.Forms;
namespace Directoryinfo_class
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
The given example will demonstrate well DirectoryInfo class. This program check for a
directory "D:\csharp" and If directory will be there it will show information of
directory else it will create a new directory D:\csharp
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace DirectoryInfo_class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string path=@"D:\csharp1";
61. }
Output
If you want to delete this directory press small y. Press any key to exit.
File Class: File class provided Static Method. It means that there is no need to
create the object of the class for access the class Methods. Take note that static
member can access through the class directly. File class is using for the File
operations in C#. We can create , delete , copy etc. operations do with C# File
class
FileInfo Class: FileInfo Class provided the Non Static Method. It means that you
will need to create the object of the class for access class methods. Class is
loaded in memory when the object of the class will be created.
In order to create a new File using C# File class , we can call Create method in the File
class.
Syntax
Before creating a File object , usually check that File exist or not. For that use the Exists
method in the C# File class.
Syntax
using System;
using System.Windows.Forms;
using System.IO;
namespace Fileinfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (File.Exists(textBox1.Text))
{
MessageBox.Show("File is already exist");
textBox2.Text = File.ReadAllText(textBox1.Text);
}
else
{
File.Create(textBox1.Text);
MessageBox.Show("File created successfully");
}
}
}
}
Step :3 Now Run the program and Enter Drive Path with File Name(textBox1.Text)--
>click the Submit button.You will see:-
if File is already Exist then values of that File will display in
TextBox(textBox2.Text).
If File is not Exist in Drive then New File will be created.
Output:
Example 2
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
FileInfo Class in C#
Example:
using System;
using System.Windows.Forms;
using System.IO;
namespace Fileinfo_class
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FileInfo finfo = new FileInfo(textBox1.Text);
if (finfo.Exists)
{
MessageBox.Show("File is already exist");
textBox2.Text = finfo.OpenRead().ToString();
}
else
{
finfo.Create();
MessageBox.Show("File created success fully");
}
}
}
}
Output:-
Note: In this above example I have created FileInfo class object(finfo) that is used for
access the class members.
The following program demonstrates well the uses of FileInfo class. This program searches for
file D:\csharp\fileinfo.txt. If the file found then it displays the information of the file else
create new file.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace FileInfo_Class
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string path = @"D:\csharp\fileinfo.txt";
C. FileStream Class
FileStream Class represents a File in the Computer. Use the FileStream class to read
from, write to, open, and close files on a file system, as well as to manipulate other file
related operating system handles including pipes, standard input, and standard output.
FileStream allows to move data to and from the stream as arrays of bytes. We operate
File using FileMode in FileStream Class.
Syntax:
FileMode – It specifies how to operation system should open the file. It has following
members
1. FileMode.Append - Open the file if exist or create a new file. If file exists then
place cursor at the end of the file. Open and append to a file if the file does not
exist , it create a new file
2. FileMode.Create - It specifies operating system to create a new file. If file
already exists then previous file will be overwritten. Create a new file , if the file
exist it will append to it.
3. FileMode.CreateNew - It create a new file and If file already exists then
throw IOException.
4. FileMode.Open – Open existing file.
5. FileMode.Open or Create – Open existing file and if file not found then create
new file.
6. FileMode.Truncate – Open an existing file and cut all the stored data. So the file
size becomes 0.
The following C# example shows , how to create and write in a file using FileStream.
Example 1:
Create a new file "CsharpFile.txt" and saves it on disk. And then open this file, saves
some text in it and then close this file.
namespace FileStream_CreateFile
{
class Program
{
static void Main(string[] args)
{
FileStream fs = new FileStream("D:\\csharpfile.txt", FileMode.Create);
fs.Close();
lblResult.Text = "File has been created and the Path is
D:\\csharpfile.txt";
Console.ReadKey();
}
}
Output:
File has been created and the Path is D:\\csharpfile.txt
Important Points :
Example:
Open csharpfile.txt and write some text in it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace AccessFile
{
class Program
{
Output:
Successfully saved file with data: Hello File Handling!
Important Points:
Example:
Read data from csharpfile.txt file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace FileStream_ReadFile
{
class Program
{
static void Main(string[] args)
{
string data;
FileStream fsSource = new FileStream("D:\\csharpfile.txt", FileMode.Open,
FileAccess.Read);
using (StreamReader sr = new StreamReader(fsSource))
{
data = sr.ReadToEnd();
}
lblResult.Text = data.ToString();
}
}
}
Output:
Lesson 2
Textreader and Text writer class
Introduction
C# has a wide array of file operations. These operations include opening a file, reading
or writing to a file. There can be instances wherein you want to work with files directly,
in which case you would use the file operations available in C#. Some of the basic file
operations are mentioned below.
1. Reading – This operation is the basic read o2peration wherein data is read from
a file.
2. Writing - This operation is the basic write operation wherein data is written to a
file. By default, all existing contents are removed from the file, and new content is
written.
3. Appending – This operation also involves writing information to a file. The only
difference is that the existing data in a file is not overwritten. The new data to be
written is added at the end of the file.
Objective:
In this module you will learn the application of File Class Textreader and
Textwriter class to create, delete, copy, etc. operations to file.
Learning Outcome:
File Info:-It supports creation, deletion open and moving of files using File Stream
object. We cannot inherit File Info class from other class.
Directory Info:- It is same as File Info class but it is used for Directory
operations(create, move, enumerate etc.).We cannot inherit Directory Info class from
other class.
BinaryReader:- It supports to Read Primitives Data Types same as binary values .
BinaryWriter:- it supports to write the primitive Data Types in Binary to a stream.
StreamWriter:-It supports to Write characters in the string Buffer.
TextReader:-It is used for reading the sequential series of characters.
TextWriter:-It is used for writing the sequential series of characters.
MemoryStream:- It supports to creates a stream in Memory .
DriveInfo:- It supports to access the information from a drive.
FileAccess:-It supports Read,Write access to a File.
1. StreamReader Class:-
Flush():- Flush function is used for immediately save the File contents
from Buffer to Memory.
Close():-Close function is used for closing the file. If we do not write close()
statement in our program then File will be always open mode ,then No other
person will be used this File at that time. This is the reason for using close
statement in the File Program.
Read()- It is used for Reading the Value using File Stream.
Read-line():-It is used for Read the value using File Stream in a File Line by
Line.
Peek():- It returns next value but not use it.
Seek():- It is used for Read/Write a values at any positions in a file.
2. StreamWriter Class:-
Note :- There are some other classes also but they are being used rarely in any real
Application.
Now let us make some real application which includes following things which is given
below:
There are some steps to perform these three tasks. Follow step by step which is given
below:
Step :2 Now make this Design using controls which is as shown below:
see it:
Step :3 Now double click on Buttons(Write,Read,Find) one by one and write the
following codes which is given below:
see it:
using System;
using System.Windows.Forms;
using System.IO;
namespace file_write
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Description:- Here the written c# codes have three purposes which is given below:
see it:
Now go to your Directory path which you have specified, you will see your File will be
created and contents of TextBox are written in the File.
Step :5 Now click on Read Button -->You will see contents are read from File and
shown in TextBox(textBox3.Text).
See it:
Step :6 Now Write some words in TextBox(textBox4.Text) for searching purpose and
Click Find Button.
Question 1. Make a D:\csharp\example.txt file using following class and Read and Write
Date and Time. You must make D:\csharp folder before executing this program
otherwise it will throw DirectoryNotFound Exception.
1. FileStream Class
2. StreamWriter and StreamReader
3. TextWriter and TextReader
FileStream
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace Example1_FileStream
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. try
15. {
16. string file = @"D:\csharp\example.txt";
17. //Creating File
18. FileStream fs = new FileStream(file, FileMode.Create);
19. //Adding current date and time in file
STREAMWRITER AND STREAMREADER
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace Example1_Stream
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\csharp\example.txt";
15. //Creating and Writting
16. using (StreamWriter writer = new StreamWriter(file))
17. {
18. writer.Write(DateTime.Now.ToString());
19. Console.WriteLine("Successfully Added Current Date and Time");
20. }
21. //Reading File
22. using (StreamReader reader = new StreamReader(file))
23. {
24. Console.Write("Reading Current Time : ");
25. Console.WriteLine(reader.ReadToEnd());
26. }
27. Console.ReadKey();
28. }
29. }
30. }
TEXTWRITER AND TEXTREADER
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace Example1_Text
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string file = @"D:\csharp\example.txt";
15. //Writting File
16. using (TextWriter writer = File.CreateText(file))
17. {
18. writer.WriteLine(DateTime.Now.ToString());
19. Console.WriteLine("Successfully Added Current Date and Time");
20. }
21. //Reading File
22. using (TextReader reader = File.OpenText(file))
23. {
24. Console.Write("Reading Current Time : ");
25. Console.WriteLine(reader.ReadToEnd());
26. }
27. Console.ReadKey();
28. }
29. }
30. }
Lesson 3
Path Class
Path Class performs operations on String instances that contain file or directory path
information. The members of the Path class enable you to quickly and easily
perform common operations such as returns filenae , extensios etc.
Example:
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{ public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string tmpPath = "c:\\windows\\inf\\wvmic.inf";
1. You are assigned to develop a project in which project manager wants following
functionality.