0% found this document useful (0 votes)
49 views30 pages

General Instructions:: Programming 2 - Module 5

This document provides an overview and lessons on file operations in C# programming. It discusses: 1. The Directory class, File class, and FileStream class which allow creating, deleting, moving, and manipulating directories and files. 2. Examples are provided showing how to use the Directory class to check if a directory exists, create a new directory, and get files in a directory. 3. The DirectoryInfo class is also discussed, which provides non-static methods for directory manipulation like the Directory class. An example shows creating a new directory using DirectoryInfo. 4. Lesson 1 focuses on the Directory class, File class, and FileStream class for directory and file operations in C#.

Uploaded by

Therish Baloran
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
49 views30 pages

General Instructions:: Programming 2 - Module 5

This document provides an overview and lessons on file operations in C# programming. It discusses: 1. The Directory class, File class, and FileStream class which allow creating, deleting, moving, and manipulating directories and files. 2. Examples are provided showing how to use the Directory class to check if a directory exists, create a new directory, and get files in a directory. 3. The DirectoryInfo class is also discussed, which provides non-static methods for directory manipulation like the Directory class. An example shows creating a new directory using DirectoryInfo. 4. Lesson 1 focuses on the Directory class, File class, and FileStream class for directory and file operations in C#.

Uploaded by

Therish Baloran
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 30

Programming 2 – Module 5

GENERAL INSTRUCTIONS:

You are under a Guided Distance Learning Mode of Delivery. To successfully


use this module, be sure to follow instructions carefully:

1. For this module you are only given:


a. A week or less than to finish this module.
2. Take good care of this module.
3. Read and understand the lessons in the module carefully.
4. Answer the Pre-test and Check-up/Reflect/Self Progress Test in the module.
5. Perform all the drills, activities, exercises and assignments in the lesson.
6. Summarize what you have learned and record important information.
7. If there is anything you do not understand in this module, see somebody or your
teacher who can help you, do research but never ask someone to do the activity
or answer the questions for you.
8. Submit your module for checking and evaluation.
9. Ask for necessary corrections and feedback from your teacher.
10.Take the online quizzes and major exams on the schedule set by the
teacher.

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

Module 5 – FILE OPERATIONS


I. Overview
Lesson 1: Directory Class, File Class and File Stream Class
Lesson 2: Textreader and Text writer class
Lesson 3: Path Class

II. General Objectives


1. Identify the different methods to create, delete, move, etc. operations to
directories and subdirectories
2. Apply the File class, Textreader and TextWriter class to create, delete, copy, etc
operations to file
3. Use the FileStream class to read from, write to, open, and close files on a file
system
4. Perform operations on String instances that contain file or directory path
information

III. References
https://www.completecsharptutorial.com
https://www.msdotnet.co.in/2013
https://www.c-sharpcorner.com
http://csharp.net-informations.com

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

Lesson 1
Directory Class, File Class and File Stream Class

Objectives:

Student able to:


 Differentiate the functions of directory class, file class and file stream class;
 Apply the different methods and properties in directory class, file class, and file
stream class
 Apply directory class, file class and file stream class in C# program

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

A. Directory and DirectoryInfo 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.

Directory class in C# exposes methods to create , delete , move etc. operations to


directories and subdirectories . Because of the static nature of C# Directory class , we do
not have to instantiate the class. We can call the methods in the C# Directory class
directly from the Directory class itself.

1. CREATE a directory using Directory class

To create a new directory using Directory class in C#, call CreateDirectory method


directly from Directory class.

Syntax

 DirPath : The name of the new directory

Note:

Before creating a directory or folder , check that directory or folder exist or not. In C#
use Exists method in the Directory class.

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

To check a directory exist or not using Directory class

Syntax

 DirPath : The name of the directory


 bool : Returns true or false

2. MOVE a Directory using Directory class in C#

To move a directory and its contents from one location to another, use the Move
method in the C# Directory class.

Syntax

 sourceDirName : The source directory we want to move.


 destDirName : The destinations directory name.

3. DELETE a Directory using Directory class in C#

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.

Example of Directory Class

Step :1 First open Your Visual studio--> File-->New-->Project->Windows Forms


Application-->OK.--> Drag and Drop controls on form  like given below:

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

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();
}

private void button1_Click(object sender, EventArgs e)


{
if (Directory.Exists(textBox1.Text))
{
String[] sfile = Directory.GetFiles(textBox1.Text);
foreach (String s in sfile)
{
comboBox1.Items.Add(s);
}
}
else
{
Directory.CreateDirectory(textBox1.Text);
MessageBox.Show("Directory created");
}
}
}
}

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

Step :3 Now Run the Program(Press F5).


OUTPUT:

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 .

Another example of C# program that shows some operations in Directory class

Example 2:

using System;
using System.Windows.Forms;
using System.IO;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
if (Directory.Exists("c:\\testDir1"))
{
//shows message if testdir1 exist
MessageBox.Show ("Directory 'testDir' Exist ");
}
else

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

{
//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:

1. DirectoryInfo class is used for typical operations such as copying, moving,


creating or deleting directories.
2. This class cannot be inherited.
3. By default full read/write access to new directories is granted to all users.

Example of DirectoryInfo Class

Step :1 First open Your Visual studio--> File-->New-->Project->Windows Forms


Application-->OK.--> Drag and Drop controls on form  like given below:

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

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();
}

private void button1_Click(object sender, EventArgs e)


{
DirectoryInfo dinfo = new DirectoryInfo(textBox1.Text);
if (dinfo.Exists)
{
FileInfo[] sinfo = dinfo.GetFiles();
foreach (FileInfo s in sinfo)
{
comboBox1.Items.Add(s);
}
}
else
{
dinfo.Create();
MessageBox.Show(" New Directory has been created");
}
}
}
}

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

Step :3 Now Run the Program(Press F5).


Output:

Description: In above Example I have created a New Directory Using DirectoryInfo


class in D   drive. In this program I have created the object of DirectoryInfo class
because DirectoryInfo class provide Non Static Method. So we need to create the object
of DirectoryInfo class. 

Get DIRECTORY DETAILS using Directory Info Class

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
 

PROGRAMMING EXAMPLES AND CODES

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";

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

15. DirectoryInfo dir = new DirectoryInfo(path);


16. try
17. {
18. if (dir.Exists)
19. {
20. Console.WriteLine("{0} Directory is already exists", path);
21. Console.WriteLine("Directory Name : " + dir.Name);
22. Console.WriteLine("Path : " + dir.FullName);
23. Console.WriteLine("Directory is created on : " + dir.CreationTime);
24. Console.WriteLine("Directory is Last Accessed on " +
dir.LastAccessTime);
25. }
26. else
27. {
28. dir.Create();
29. Console.WriteLine(path + "Directory is created successfully");
30. }
31. //Delete this directory
32. Console.WriteLine("If you want to delete this directory press small y.
Press any key to exit.");
33. try
34. {
35. char ch = Convert.ToChar(Console.ReadLine());
36. if (ch == 'y')
37. {
38. if (dir.Exists)
39. {
40. dir.Delete();
41. Console.WriteLine(path + "Directory Deleted");
42. }
43. else
44. {
45. Console.WriteLine(path + "Directory Not Exists");
46. }
47. }
48. }
49. catch
50. {
51. Console.WriteLine("Press Enter to Exit");
52. }
53. Console.ReadKey();
54. }
55. catch(DirectoryNotFoundException d)
56. {
57. Console.WriteLine("Exception raised : " + d.Message);
58. }
59. }
60. }

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

61. }

Output

D:\csharp1Directory is created successfully

If you want to delete this directory press small y. Press any key to exit.

B. File and FileInfo Classes


These Classes can be used to do some manipulation and to set some information
regarding the File.

 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.

1. CREATE a File using C# File class ?

In order to create a new File using C# File class , we can call Create method in the File
class.

Syntax

 FilePath : The name of the new File Object

2. Check a File exist or not using C# File class

Before creating a File object , usually check that File exist or not. For that use the Exists
method in the C# File class.

Syntax

 FilePath : The name of the File


 bool : Returns true or false

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

Example of File class:

Step :1  First Open your visual studio-->File-->New-->Project-->Windows forms


Application -->click OK-->And make the design which is given below:
see it:

Step :2 Double click on Submit button and Write the following codes:

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");
}
}

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

}
}
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();
}

private void button1_Click(object sender, EventArgs e)


{
if (File.Exists("c:\\testFile.txt"))
{
//shows message if testFile exist
MessageBox.Show ("File 'testFile' Exist ");
}
else
{

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

//create the file testFile.txt


File.Create("c:\\testFile.txt");
MessageBox.Show("File 'testFile' created ");
}
}
}
}

FileInfo Class in C#

FileInfo class in c# is used for manipulating file as creating, deleting, removing, copying,


opening and getting information. It provides properties and instance methods that
makes file manipulation easy.
Important points:

1. FileInfo class is used for typical operation like copying, moving, renaming,


creating, opening, deleting and appending the file.
2. By default, full read/write access to new files is granted to all users.

 Example of FileInfo class:


FileInfo class has some steps which is similar to File Class.

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");
}

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

}
}
}

Output:-

Note: In this above example I have created FileInfo class object(finfo) that is used for
access the class members.

Use FileInfo to manipulate file

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.

Programming examples and codes

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";

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

15. FileInfo file = new FileInfo(path);


16. //Create File
17. using (StreamWriter sw = file.CreateText())
18. {
19. sw.WriteLine("Hello FileInfo");
20. }
21.  
22. //Display File Info
23. Console.WriteLine("File Create on : " + file.CreationTime);
24. Console.WriteLine("Directory Name : " + file.DirectoryName);
25. Console.WriteLine("Full Name of File : " + file.FullName);
26. Console.WriteLine("File is Last Accessed on : " + file.LastAccessTime);
27.
28. //Deleting File
29. Console.WriteLine("Press small y for delete this file");
30. try
31. {
32. char ch = Convert.ToChar(Console.ReadLine());
33. if (ch == 'y')
34. {
35. if (file.Exists)
36. {
37. file.Delete();
38. Console.WriteLine(path + " Deleted Successfully");
39. }
40. else
41. {
42. Console.WriteLine("File doesn't exist");
43. }
44. }
45. }
46. catch
47. {
48. Console.WriteLine("Press Enter to Exit");
49. }
50. Console.ReadKey();
51. }
52. }
53. }

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.

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

FileStream allows to move data to and from the stream as arrays of bytes. We operate
File using FileMode in FileStream Class.

Use filestream class in c#

Syntax:

FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>,


<FileAccess Enumerator>, <FileShare Enumerator>);

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.

FileAccess – It gives permission to file whether it will


open Read, ReadWrite or Write mode. FileShare – It opens file with following share
permission.

1. Delete – Allows subsequent deleting of a file.


2. Inheritable – It passes inheritance to child process.
3. None – It declines sharing of the current files.
4. Read- It allows subsequent opening of the file for reading.
5. ReadWrite – It allows subsequent opening of the file for reading or writing.
6. Write – Allows subsequent opening of the file for writing.

Create a file using C# FileStream Class

The following C# example shows , how to create and write in a file using FileStream.

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

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.

// Create a blank .txt file using FileStream


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

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 :

 System.IO namespace allow you to use FileStream class in the program.


 Create an object of FileStream class fs to create a new csharpfile.txt in D drive.

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
{

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

static void Main(string[] args)


{
FileStream fs = new FileStream("D:\\csharpfile.txt", FileMode.Append);
byte[] bdata=Encoding.Default.GetBytes("Hello File Handling!");
fs.Write(bdata, 0, bdata.Length);
fs.Close();
lblResult.Text = "Successfully saved file with data : Hello File Handling!";
}
}
}

Output:
Successfully saved file with data: Hello File Handling!

Important Points:

 Create an object like fs of FileStrem class.


 Encode a string into bytes and kept into byte[] variable bdata.
 Use Write() method of FileStream to store string into file.

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:

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

Hello File Handling!

Lesson 2
Textreader and Text writer class
Introduction

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

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:

 Apply some of the important classes used in File Operations.

They will be discussed each through example below:

File Stream:- It supports both Read and Write operations in a File.

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.

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

 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:-

 close()-->Close function is used for closing the file.


 Flush():-Flush function is used for immediately save the File contents
from Buffer to Memory.
 Write():- It is used for writing a File using File stream class.
 WriteLine():- It is used to write a File Line by Line using File stream.

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:

 Writing the Contents in a File.


 Reading the contents from the File.
 Finding the Word from the File.

There are some steps to perform these three tasks. Follow step by step which is given
below:

Step :1  First open Your visual studio-->File -->New-->Project-->Select Windows Forms


Application-->OK.

Step :2 Now make this Design using controls which is as shown below:
see it:

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

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();
}

private void button1_Click(object sender, EventArgs e)


{
FileStream fs = new FileStream(textBox2.Text, FileMode.Create,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(textBox1.Text);
sw.Flush();
fs.Close();
MessageBox.Show("Content is written in file successfully");
}
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(textBox2.Text, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
textBox3.Text = sr.ReadToEnd();
fs.Close();

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

private void button3_Click(object sender, EventArgs e)


{
FileStream fs = new FileStream(textBox2.Text, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
String str = sr.ReadToEnd();
int i = (str.IndexOf(textBox4.Text,0));
if (i >-1)
{
MessageBox.Show("This word is exist in the file");
}
else
{
MessageBox.Show("This word is not exist in the file try another words");
}
}
}
}

Description:- Here the written c# codes have three purposes which is given below:

 Button1 click-->Writing the Contents in a File Using c# programming.


 Button2 click--> Reading the contents from File Using c# programming.
 Button3 click--> Searching the word from File using c# programming.

Step :4 Now  Run the program(Press F5). In Upper TextBox (textBox2.Text) -->Write


Your Directory Path and File Name-->Now Write the contents which you want to write
in TextBox(textBox1.text)-->and click Write Button. You will see which is shown below:

see it:

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

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.

You will see:

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

Other programming examples for further understanding:

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

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

20. byte[] bdata = Encoding.Default.GetBytes(DateTime.Now.ToString());


21. fs.Write(bdata, 0, bdata.Length);
22. Console.WriteLine("Data Added");
23. fs.Close();
24. //Reading File
25. string data;
26. FileStream fsread = new FileStream(file, FileMode.Open,
FileAccess.Read);
27. using (StreamReader sr = new StreamReader(fsread))
28. {
29. data = sr.ReadToEnd();
30. }
31. Console.WriteLine(data);
32. }
33. catch (Exception e)
34. {
35. Console.WriteLine(e.Message.ToString());
36. }
37. Console.ReadKey();
38. }
39. }
40. }

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))

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

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

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

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.

Important operations in C# Path Class:


 GetDirectoryName - Returns the directory information for the specified path
string.
 GetExtension - Returns the extension of the specified path string.
 GetFileName - Returns the file name and extension of the specified path string.
 GetFileNameWithoutExtension - Returns the file name of the specified path
string without the extension.
 GetFullPath - Returns the absolute path for the specified path string.

Get Current Application Path


C# Class application in System.Windows.Forms namespace has static property
called ExecutablePath . To get the current application path we can use
GetDirectoryName of Path class with ExecutablePath as parameter.

It will return the current directory path of the .exe file .

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";

string fileExtension = Path.GetExtension(tmpPath);


string filename = Path.GetFileName(tmpPath);
string filenameWithoutExtension =
Path.GetFileNameWithoutExtension(tmpPath);
string rootPath = Path.GetPathRoot(tmpPath);
string directory = Path.GetDirectoryName(tmpPath);
string fullPath = Path.GetFullPath(tmpPath);
MessageBox.Show(directory);
}
}
}

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto


Programming 2 – Module 5

Module 5 - Laboratory Activity:

1. You are assigned to develop a project in which project manager wants following
functionality.

1. Create Student Folder in D drive using DirectoryInfo class.


2. Ask student's name and create a file with that name and store in Student folder.
3. Ask student's details and save information in that file.
Student details :
a. Name
b. Age
c. Address
d. Year level
4. Print following option on a label.
a. View Saved File
b. View Directory Details

Prepared by : Estela L. Dirain ; Marie Khadija Xynefida P. Ontiveros; Jesty A. Agoto

You might also like