1. Introduction
In any real-world ASP.NET project, file handling is essential—whether you’re saving logs, generating reports, or managing uploaded files.
C# makes this process simple using the System.IO namespace, which provides classes such as:
File – For simple file operations.
StreamReader / StreamWriter – For reading and writing text.
FileInfo, Directory, Path – For managing files and folders.
2. Common Real-Time Use Cases in Web Applications
| Scenario | Purpose |
|---|
| Save Logs | Save error or user activity logs in text files. |
| Upload Files | Upload user files and save them on the server. |
| Read Reports | Read data from stored files. |
| Export Data | Create text-based or CSV reports. |
| Manage Files | Delete or rename temporary files. |
3. Real-Time Example: File Handling in ASP.NET Web Forms
Let’s create a simple WebForm that performs three operations:
Write to a file – save user input
Read file content – show it in a text box
Delete the file – remove it when not needed
Step 1: Create a WebForm – FileHandler.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileHandler.aspx.cs" Inherits="FileHandler" %>
<!DOCTYPE html>
<html>
<head>
<title>File Handling in ASP.NET Web Forms</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width:600px; margin:auto; text-align:center; font-family:Arial;">
<h2>📂 File Handling Example (Read / Write / Delete)</h2>
<asp:Label ID="lblInfo" runat="server" Text="Enter some text:" /><br />
<asp:TextBox ID="txtContent" runat="server" TextMode="MultiLine" Rows="5" Width="400px"></asp:TextBox><br /><br />
<asp:Button ID="btnWrite" runat="server" Text="Write to File" OnClick="btnWrite_Click" />
<asp:Button ID="btnRead" runat="server" Text="Read File" OnClick="btnRead_Click" />
<asp:Button ID="btnDelete" runat="server" Text="Delete File" OnClick="btnDelete_Click" /><br /><br />
<asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="Green"></asp:Label>
</div>
</form>
</body>
</html>
Step 2: Code Behind – FileHandler.aspx.cs
using System;
using System.IO;
public partial class FileHandler : System.Web.UI.Page
{
string filePath = HttpContext.Current.Server.MapPath("~/App_Data/UserData.txt");
protected void Page_Load(object sender, EventArgs e)
{
// Ensure directory exists
string directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
// WRITE TO FILE
protected void btnWrite_Click(object sender, EventArgs e)
{
try
{
string content = txtContent.Text;
// Write text to file
File.WriteAllText(filePath, content);
lblMessage.Text = " Data written to file successfully!";
}
catch (Exception ex)
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = " Error: " + ex.Message;
}
}
// READ FILE CONTENT
protected void btnRead_Click(object sender, EventArgs e)
{
try
{
if (File.Exists(filePath))
{
string data = File.ReadAllText(filePath);
txtContent.Text = data;
lblMessage.Text = " File content loaded successfully!";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = " File not found!";
}
}
catch (Exception ex)
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = " Error: " + ex.Message;
}
}
// DELETE FILE
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
txtContent.Text = "";
lblMessage.Text = " File deleted successfully!";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = " File does not exist!";
}
}
catch (Exception ex)
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = " Error: " + ex.Message;
}
}
}
4. Output Examples
Write to File:
Enter text in textbox → Click “Write to File”
Message: “Data written to file successfully!”
Read File:
Click “Read File” → The saved text appears in the textbox.
Delete File:
Click “Delete File” → Message: “File deleted successfully!”
5. Behind the Scenes
| Function | Method Used | Description |
|---|
| Write File | File.WriteAllText() | Creates/Overwrites a text file. |
| Read File | File.ReadAllText() | Reads complete text from file. |
| Delete File | File.Delete() | Deletes the file from server path. |
| Folder Path | Server.MapPath() | Converts virtual path to physical path. |
6. Real-Time Business Use Cases
| Use Case | Example |
|---|
| Logging System | Save user activity logs (login/logout). |
| Report Export | Write order details or invoices to text/CSV. |
| Data Backup | Save configuration data temporarily. |
| Upload Feature | Combine uploaded file metadata with text info. |
| Error Handling | Store exception logs in App_Data/errorlog.txt. |
7. Advanced Example: Append and Read Line-by-Line
// Append text to an existing file
File.AppendAllText(filePath, "\nNew entry added at: " + DateTime.Now);
// Read file line by line
foreach (string line in File.ReadAllLines(filePath))
{
Response.Write(line + "<br/>");
}
8. Best Practices for File Handling in ASP.NET
Always use Server.MapPath() for physical file path mapping.
Use the App_Data folder for storing text/log files (not accessible directly from the browser).
Implement try-catch blocks to handle file exceptions.
Check File.Exists() before reading or deleting.
Use locks or async file methods in high-load applications.
9. Conclusion
File handling in C# makes it easy to read, write, and manage files directly from ASP.NET Web Forms applications.
From saving logs to exporting data reports, it’s a fundamental skill that every developer must master to create efficient and data-driven web applications.
By using classes like File, StreamWriter, and Directory, you can manage your application’s files with just a few lines of code.