In many software applications, the ability to read and write files is essential. Whether it’s reading configuration files, processing user data, or generating reports, file handling is a common task. In this guide, we will explore how to work with files in C# and perform read and write operations efficiently.
File I/O?
File I/O refers to the process of reading data from and writing data to files on a disk. It allows applications to interact with persistent storage and retrieve or store information.
Reading Files in C#
Reading files in C# using System.IO.File class. We’ll explore how to read the content of a file using the File.ReadAllText method. Additionally, we’ll cover techniques for reading files line by line or working with large files efficiently using buffered reading.
Writing Files in C#
To write data to files in C#, we’ll leverage the File.WriteAllText method provided by the System.IO.File class. We’ll show how to create new files.
Here is a step by step explanation of how to read and write a file
Step 1:
To read and write files, include the following namespaces
using System.IO;
using Microsoft.AspNetCore.Mvc;
Step 2:
Create a model class
namespace Files_Sample.models
{
public class FileModel
{
public string FilePath { get; set; }
public string Content { get;set; }
}
}
Step 3:
Example Code:
using Files_Sample.models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
namespace Files_Sample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FileController : ControllerBase
{
[HttpPost]
public IActionResult Write(FileModel data)
{
try
{
System.IO.File.WriteAllText(data.FilePath, data.Content);
return Ok();
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
[HttpGet]
public IActionResult Read(string filePath)
{
try
{
if (System.IO.File.Exists(filePath))
{
string fileContent = System.IO.File.ReadAllText(filePath);
return Ok(fileContent);
}
else
{
return NotFound();
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}
Explanation:
Write data to a file.
public IActionResult Write(FileModel data)
{
try
{
System.IO.File.WriteAllText(data.FilePath, data.Content);
return Ok();
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
The write action is an HTTP POST endpoint that receives a FileModel object (data) representing the file to be written.
Inside the action, it attempts to write the data.Content to the file specified by data.FilePath using System.IO.File.WriteAllText method.
If the write operation is successful, it returns an HTTP 200 OK response. Otherwise, it catches any exceptions that occur and returns an HTTP 400 Bad Request response with the exception message.
Read a data from file.
public IActionResult Read(string filePath)
{
try
{
if (System.IO.File.Exists(filePath))
{
string fileContent = System.IO.File.ReadAllText(filePath);
return Ok(fileContent);
}
else
{
return NotFound();
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
The read action is an HTTP GET endpoint that receives a filePath parameter representing the path to the file to be read.
Inside the action, it checks if the file exists using System.IO.File.Exists(filePath). If the file exists, it reads the content of the file using System.IO.File.ReadAllText(filePath) and returns the content as an HTTP 200 OK response. If the file does not exist, it returns an HTTP 404 Not Found response.
Step 4:
Run the code.
POST (Write):
filePath- provide your file path with file name where you want to create a file.
It creates a file named Hello with the content “Hello world..!!!”
GET(Read) :
filePath- provide your file path which you want to read.
It returns the content of the file.
This blog provides a basic implementation of a Web API controller for handling file read and write operations. It demonstrates how to use the System.IO.File class to perform file I/O operations and how to handle exceptions that may occur during those operations.
No Comment! Be the first one.