UNIT IIT
FILE HANDLING
—_———--——---
1. FILE STREAM CLASSE!
The FileStream class in C# (part of Systens.10) is used for wi
Teading and writing raw bytes. IL allows developers to open,
stream-based approach,
‘orking with files at a low level by
read, write, and close files using a j
FileStream is commonly used when:
+ You want to read/write
ary data,
+ You need full control over file access, creation, and sharing.
* You want to use FileMode, FileAccess, and FileShare settings together.
Constructor Syntax: || /
FileStream fs = new FileStream(string path, FileMode mode, FileAccess access, FileShare
share);
- path: The path to the file.
= mode: How to open/create the file (c.g., Create, Open). |
~ access: Permission level (Read, Write, Read Write). |
~ share: File sharing option (¢.g., None, Read). {
: ‘
- FileStream works at the byte Iével., c
- Itis ideal for reading and writing binary files like images, audio, or custom formats.
~ Always use
ing! to ensure the file is properly closed, L
- Can be combined with StreamReader/Writer of
aryReader/Writer for more specific tasks.
+ FileStream ~ for reading and writing bytes to a file,
+ StreamReader — for reading characters from a stream,
+ StreamWriter — for writing characters to a stream, /+ BinaryReader / BinaryWriter — for working with binary data.
Example (Writing to a File):
using (FileStream f = new FileStream("sample.txt", FileMode.Create))
{
byte[] data = Encoding.UTF8.GetBytes("Hello World!");
| f.Write(data, 0, data.Length);
3
Explanation:
1. using (FileStream fs = new FileStream("sample.txt", FileMode.Create))
~ Opens or creates a file named 'sample.txt' using FileMode.Create.
= Ifthe file already exists, it is overwritten.
~The using! statement ensures the ile is automatically closed when done: ggaus
ne buted
pvortebe widly choree “\
a db
ve Untboda Tronforrmedian Foreat
2. bytef] data = Encoding. UTF8.GetBytes("Hello World!"
a —
~ Converts the string "Hello World!" into a byte array using UTF-8 encoding.
- FileStream handles binary data, so we must convert text to bytes.
3. f5.Write(data, 0, data. Length);
~ Writes the byte array into the file from index 0 to the end.
- The entire message is written into the file.
Result:
~A file named 'sample.txt’ is created (or replaced if it exists).
~ The text "Hello World!" is written inside it.
~ The file is safely closed after the operation completes.2, FILE MODES IN .NET (FileMode)
‘The FileMode enumeration in C#f defines how the operating system should open or create
a file when a FileStream or File-based method is called.
© It is found in the S,
stem.IO namespace and works with classes like FileStream,
BinaryReader, BinaryWriter, and others, :
The choice of FileMode affects:
+ Whether a file must already exist or not,
+ Whether its contents will be preserved, erased, or appended.
+ Whether errors will be thrown ifthe file exists or doesn’t exist.
The following are the six common FileMode values, each with practical uses:
six common FileMod¢
oO FileMode.Create
Purpose:
~ Creates a new file. If the file already exists, it is completely overwritten.
Typical Use:
~ Use when you want to start fresh, regardless of whether a file with the same name exists.
System Behavior:
~ Ifthe file exists, itis truncated (emptied) before writing,
- If the file doesn’t exist, it is created, .
Example:
FileStream fs = new FileStream("log.txt", FileMode.Create);
Explanation:
Anew file named ‘log.txt! is created, If'log.txt' already exists, it is deleted and replaced witha
————
new empty file.Mode.CreateNew
Purpose:
= Creates a new file. If the file already exists, throws an IOException.
eee
Typical Use:
~ Use when you want to pr
nt accidental overwriting of existing files.
System Behavior:
~ Throws an exception if the file already exists.
~ Ensures only new files are created.’
Example:
FileStream fs = new FileStream("report.txt", FileMode.CreateNew);
Explanation:
‘Report.tat’ is created only if it doesn't exist. An exception is thrown if it already does, making
this mode safer for critical operations. "RE
leMode.Open
oer
Purpose:
- Opens an existing file. If the file does not exist, it throws a FileNotl
FoundException.
Typical Use:
- Use when you are sure the file exists and you only want to work with existing data.
System Beha
- No file creation occurs.
- The stream opens for read/write access depending on FileAccess setting.
Example:
FileStream fs = new FileStream("data.txt", FileMode.Open);
Explanation:
Opens ‘data.txt' for operations. If the file does not exist, the code fails with an exception. Useful
for configuration files, logs, etc.FileMode.OpenOrCreate
Purpose:
= Opens an existing file if present, otherwise creates a new one,
Typical Use: ;
Jse when you want your program to proceed regardless of file presence.
i
System Behavior:
No Grrr is thrownhwhether the file exists.or not.
- Thihe file exists, itis opened; otherwise, i
Example:
FileStream fs = new FileStream(""config.t
", FileMode.OpenOrCreate);
If ‘config.txt’ exists, it is opened for use. If it doesn’t, a new file is created — very useful for
app settings, logs, or caching.
FileMode.Append
Purpo:
= Opens the file if it exists and appends data to the end. If it doesn't exist, a new file is created.
Typical Use:
- Use when maintaining logs or cumulative reports.
System Behavior:
- The file pointer is positioned at the end of the file.
- Only writing is allowed; reading is not supported with Append mode.
Example:
FileStream fs = new FileStream(“output.txt", FileMode.Append);
Explanation:
Data is always added after existing content in ‘output.txt’, It will not delete or modify carlier
content. Ideal for logging or audit trail “
FileMode.Truncate
Purpose:
~ Opens an existing file and deletes all its contents without deleting the file itselfTypical Use:
\ - Use when you want to ret ing file name but clear its content first.
System Behavior:
- Tiyows an erro] if the file doesn’t exist.
~ Resets the file length to 0.
Example:
FileStream fs = new FileStream("temp.txt", FileMode. Truncate);
Explanation:
Opens 'temp.txt’ and erases all content, The file still exists but becomes empty. Useful when
resetting log files or preparing a file for fresh input. e
Summary of FileMode Behavior:
FileMode If File Exists If File Does Not | Description
Exist
Create Overwrites the file _ | Creates a new file Creates or overwrites
; a'file with fresh data.
CreateNew Throws an error Creates a new file Ensurés a new file;
avoids accidental
F overwrite.
Open ‘Opens the file Throws an error {> | Opens existing “file;
? fails if missing:
‘OpenOrCreate Opens the file Creates anew file [Opens if present;
creates if missing.
‘Append Appends to end of| Creates anew file | Appends data; ddes
file not erase’ existing
content.
‘Truncate Clears file content * | Throws an error Deletes content but
i retains the file itself.
3. FILE SHARE IN-NET (FileShare)
* The FileShare enumeration in C# specifies how a file should be shared with other processes
while itis open. It defines what types of access (read/write/delete) other programs can have
to the same file concurrently, .
* Tis used along with FileStream when opening a file. This is especially important when
multiple applications or users need access to the same file at the same time.« Each FileSh:
lare option allows you to control the file locking behavior, preventing or
allowing simultaneous file access.
Common scenarios:
* Preventit i ifyil
Preventing others from reading or modifying a sensitive file during use.
+ Allowing others to read logs while one process writes,
+ Supporting collaborative editing tools where multiple users write concurrently-
Below are the commonly used FileShare modes with examples and explanations:
os dee?
FileShare.None ok
°
- Description: Exclusive access to the file. No other process can read, write, or delete the file.
d during use (e.g., configuration or credentials file).
+ Use Case: When a file must bi
- Example:
FileStream fs (= new FileStream("data.txt", FileMode.Open, FileAccess.ReadWrite,
FileShare.None);
- Explanation:
- Opens "data.txt" for both reading and writing.
= While this file is open, **no other process** can access it in any way.
- Best used when security or data integrity is critical during operations.
FileShare.Read
- Description: Allows other processes to read the file, but not write or delete it.
= Use Case: One process writes of reads, while others only need read-only access (¢.g., log
viewers).
~- Example: {
FileStream fs = new FileSteate1. txt", FileMode.OpenOrCreate, FileAccess.ReadWrite,
FileShare.Read);
- Explanation:
|
~ Opens "log.txt" for reading and writing.
- Other programs can **only read** the file while it's open.+ They cannot write to or delete the file du
ing this time,
FileShare.Write
~ Description: Allows other
esses to write to the file, but not read from it
= Use Case: Multiple programs write to a shated log or queue, but no reading is required during
‘that time,
- Example:
FileStream fs = new FileStream("upload.txt", FileMode.OpenOrCreate, FileAccess.Write,
FileShare. Write);
- Explanation:
= Opens “upload.txt" for writing.
~ Other process bar in r**, but none can **: ** from
it while it's in use.
FileShare.ReadWrite
= Description: Allows other processes to read from and write to the file at the same time.
- Use Case: Shared access by, multiple usérs or systems that need flll access t6 the same file.
- Example:
FileStream fs = new FileStream("'shared.txt", FileMode.Open, FileAccess.ReadWrite,
FileShare.ReadWrite);
- Explanation:
- Other programs can **read and sirite**to the file while i's open.
- Useful for collaborative tools or logs that are updated and read by multiple processes
FileShare.Delete 4
- Description: Allows other processes to d
e the file even
va
~ Use Case: When temporary files are created thit may need to he deleted by cleanup jobs.~ Example:
FileStream fs = new FileStream("tempfilext", FileMode.Open, FileAccess.Read,
FileShare.Delete);
~ Explanation:
- Opens "tempfile.txt" for reading
= While this file is in use, another process **can delete** it (c.g,, cleanup utility).
~ Usefial in scenarios where temporary files are short-lived or managed externally.
4. READING AND WRITING TO FILES.
There are two types of operations:
1. Text-based operations: Use strings (StreamReader, StreamWriter, File, WriteAlIText, ete.)
2
‘ary operations: Use byte arrays (FileStream, BinaryReader, BinaryWriter)
WRITING TEXT TO FILES
a) File.WriteAllText()
- Description: Writes a complete string to a file. Jf the file does not exist, it is created. If it
already exists, its content is overwritten, x ~
- Example:
File. WriteAllText(“notes.txt", "Welcome to File Handling in C#!
- Explanation:
This writes the text "Welcome to File Handling in C#!" into, the file "notes.txt".
If the file doesn't exist, it is created, If it exists, the previous content is deleted and replaced.
b) File.AppendAllText()
- Description: Appends new content to the end of a file, If the file doesn’t exist, it ereates one.eer.
- Example:
File.AppendAlIText("log.txt
"App started at " + DateTime,Now);
~ Explanation:
This appends a new
1 with a timestamp to “log.txt",
Old data remains untouched; new content is added at the end,
c) StreamWriter
~ Description: Provi
Sa way to write text ine-by-line.wvith buffering and enco
~ Example:
using (StreamWriter writer = new StreamWriter("students.txt"))
{
writer. WriteLine(""Student Name: John");
writer. WriteLine("Roll No: 101");
}
- Explanation:
‘This code creates or opens "students.txt" and writes two lines into
Itis ideal for structured, multi -
The “us
block ensures the file is automatically closed after writi
READING TEXT FROM FILES
a) File.ReadAllText()
- Description: Reads the entire content of a text fi
into a single stein
- Example:
string dat
ile ReadAllText("notes.txt");
- Explanation:
The contents of "notes.txt" are read and stored into the variable ‘data’,
Suitable for small files where you ne
ed the entire content atone.b) File.ReadAllLines()
DescHintion: R
cription: Reads the content line-by-line and returns a string array.
= Example:
string[] lines = File. ReadAllLines("students.txt
foreach (string line in lines)
A
Console. WriteLine(line);
}
- Explanation:
Reads each line from 'students.txt" into the ‘lines’ array.
/Bach line can be processed or displayed individually.
c) StreamReader
reading large files line-by-line using minimal memory.
- Example:
using (StredmReader reader = new StreamReader("students1xt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{ (
Console, WriteLine(line);
}
- Explanation:
Opens "students.txt" and reads itline-by-line inside.aloop.
‘The file is automatically-closed when the block ends.
iynamically
ing processed d
Best used for large files or fifiles and quick access.
handing
+ Always use ‘using’ blocks or manually close the streams to prevent file locking.
* For collaborative or coi
neurrent file access, use appropriate FileShare modes.
FileShare If File Is Opened | Other Processes Use Case7
With This Mode... Can... Description
None File is exclusively | Not read, not write, Full exclusive
locked not delete access; no sharing
allowed.
Read File is opened for | Read only
read/write Allow read-only
access to others (e.g.,
logs).
Write File is opened for | Write only, |
writing a Allow — concurrent
ri writing but no
reading.
ReadWrite File is opened. for | Read and write
read/write 3 Shared read-write
access’ (e.g, team
use).
Delete File is opened Delete it 7
eae a Allows another
process to delete
while open.
5. CREATING, MOVING, COPYING, AND DELETING FILES
‘These methods are widely used in applications involving data storage, backup systems,
logging, or cleaning up temporary files.A) Creating a File
Description:
Creates a new file at the specified path. If the file already exists, it can be overwritten.
Example:
File.Create("newfile.txt"),Close();
Explanation:
= File.Create("newfile.txt")': Creates an empty file named ‘newfile.txt’
= *,Close()": Immediately closes the file stream returned by ‘Create()’ to release the lock.
= If the file already exists, it is overwritten.
Code with Validation:
string path
‘data.txt";
if ({File.Exists(path))
{
File.Create(path).Close();
Console. WriteLine("File created.
else
Console. WriteLine("File already exists,
3
Explanation:
«string path = “data.txt"; + defines the file path.
+ File.Exists(path) — checks if the file already exists.
© [fit does not exist
ile.Create(path) creates it,
= Close() releases the handle so the file isn’t locked.
Message confirms the action taken.
UseCase:
Creating config files, logs, or reports only if they don't already exist.Copying a
Description:
Creates a duplicate of an existing file. Can overwrite if allowed
Example:
File.Copy(“originalxt”, "copy.txt”, tre):
Explanation:
+ “original.txt" is the source file,
+ “eopy:txt" is the destination file.
+ trucallows ovenvriting if the target already exists.
Code Without Overwriting:
File.Copy(“data.txt”, "data_backup.txt");
Ifdata_backup.txt exists, this throws an exception,
Code With Try-Catch:
ny
{
File.Copy("“data.txt", "data_backup.txt", true);
Console. WriteLine("File copied successfilly.
}
catch (IOException ex)
{
Console. WriteLine("Copy failed: " + ex.Message);
3
Explanation:
+ File.Copy(...) attempts to copy the file.
+ Ifsomething goes wrong (e.g., access denied), i's caught and handled with a message.
UseCase:
Creating backups before overwriting or processing a file,
C) Moving or Renaming a File
Description:
Moves a file to a new directory or renames it, If the dest
thrown.
ion file already exists, an error is
iExample 1; Moving
File Move("data.txt", @archive\datatxt");
Example 2: Renaming
File. Move(“oldname.txt",
Explanation:
newname.\xt");
Tn the second, oldname.txt is renamed to newname.txt
Safer Version:
if File. Exists("data.txt") && !File.Exists(@"archive\data.txt"))
{
File Move("data.txt", @"archive\datatxt");
~ Console. WriteLine("File moved.");
}
else
{
Console. WriteLine("Move failed: file already exists or not found.");
}
Explanatior
= File.Exists(...) ensures source exists and destination doesn't.
+ File.Move(...) performs the move.
‘+ Console output confirms success or failure,
UseCase:
“Archiving logs, organizing uploads, or renaming temporary files.
Inthe first case, the file data.txt is moved into a folder named archive.
D) Deleting a File
Description:
Removes a file from disk permanently. Does not move to Recycle Bin,
Example:
File.Delete(“unwanted.txt
Explanation:
«Deletes unwanted.txt from the file system.+ Ifthe file doesn’t exist, no exception is thrown,
Safer Version with Check:
if FileExists(“oldlog.txt"))
{
File-Delete("“oldlog.txt
Console. WriteLine("File deleted.");
else
Console. WriteLine("File not found.
}
‘Try-Catch Example:
ty
{
File Delete("lockedfile.txt");
Console. WriteLine("File deleted.
}
catch (IOException ex)
{
Console. WriteLine("Error deleting fi
}
Explanation:
+ ex.Message);
+ File Exists(...) ensures the file is present.
+ File.Delete(...) attempts to delete it.
+ Exceptions are caught and logged to avoid crashing the program.
UseCase:
Cleaning up temporary files, old logs, failed uploads, ete.File Operations
+ Always check if a file exists before deleting or overwriting,
+ Use try-catch to handle access issues, disk failures, or path errors,
+ Close file streams before trying to delete/move files.
+ Use absolute paths when working outside your project directory.
+ For concurrent access, combine with FileShare settings to manage locks.
6. FILE UPLOADING IN ASP.NET WEB FORMS
What is File Uploading?
File uploading allows users to send files (e.g., images, documents, videos) from their local
device to the server where the web application is hosted.
How ASP.NET Web Forms Handles File Uploads:
ASPNET uses the
control to render'a "Choose File" input element on the
page. The file is only accessible once the form is submitted. On the server-side, we can access
this file using the control's properties and save it to a server folder.
Important FileUpload Properties:
+ HasFile — Checks ifa file has been selected.
+ FileName — Retrieves the name of the uploaded file.
+ PostedFile — Gives access to metadata like content length, type, etc.
* Validate file extension to allow only safe formats (e.
g, -pdf).
+ Restrict file size using web.config or code to ave
overload.
+ Sanitize file names and paths to prevent directory traversal attacks,
+ Save files to a dedicated folder with restricted access (¢.g., ~/Uploads).
ASPX Code:
inUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
IbIMessage" runa
server" />Code-Behina:
Protected void binUpload_Click(object sender, EventArgs c)
{
if FileUploadt HasFile)
{
string folderPath = Server. MapPath("~/Uploads!");
string filePath = folderPath + FileUpload|. FileName;
FileUpload1.SaveAs(filePath);
ToIMessage. Text = "File uploaded successfilly!";
; (
else
{
IblMessage.Text = "Please select a file to upload.";
}
}
Explanation:
- FileUpload.HasFile checks if the user selected a file.
- Server. MapPath gets the physical path for the Uploads folder.
- SaveAs() saves the file to the server,
~ The label displays a success or error message.
- The upload process is triggered only when the submit button is clicked.
- Always validate file extension and size.
- Use unique names or timestamps to! prevent overwrites,
~ Ensure the upload folder exists and has write permission,
- Provide user-friendly error messages if upload fails,