LEARNING OUTCOME 7
FILE STREAMS IN C#
In C#, file streams offer a mechanism to interact with files on the storage device, enabling you to read from, write to, or manipulate files programmatically. The System.IO
namespace provides essential classes for file stream operations.
Definition:
- A file stream represents a connection to a file on disk. It acts as a conduit for transferring data between your program and the file's contents.
- File streams operate in a byte-oriented manner, meaning they work with data as a sequence of bytes, regardless of the file's actual content (text, images, etc.).
TYPES OF FILE STREAMS:
C# offers two primary types of file streams:
- FileStream: The most fundamental class for working with files. It provides both read and write capabilities.
- StreamWriter/StreamReader: These higher-level classes built on top of `FileStream` simplify working with text files.
FileStream:
- You can create `FileStream` objects using different constructors, specifying the file path, access mode (read, write, create, etc.), and other options.
- It's essential to open a file stream in the correct mode to avoid errors. Opening a file for reading when it doesn't exist would result in an exception.
-
Example:
C#
using (FileStream fileStream = File.OpenRead("myfile.txt")) { // Read data from the file using ReadByte(), Read(), etc. }
StreamWriter/StreamReader:
- StreamWriter: Used for writing text to a file. It automatically handles text encoding (e.g., UTF-8).
- StreamReader: Used for reading text from a file. It provides methods like `ReadLine()` for reading lines of text efficiently and handles decoding characters.
-
Example:
C#
using (StreamWriter writer = new StreamWriter("output.txt")) { writer.WriteLine("Writing text to a file."); } using (StreamReader reader = new StreamReader("myfile.txt")) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); // Read each line of text } }
INTERACTING WITH DATABASES IN C# USING ADO.NET
ADO.NET (Active Data Objects.NET) is a set of technologies in C# that enables interaction with various relational and non-relational databases. Here's an overview of the ADO.NET object model and an example program demonstrating database interaction:
ADO.NET Object Model:
- Data Provider: Acts as a bridge between your C# code and the specific database you're working with (e.g., SQL Server, Oracle, MySQL).
- Connection: Represents a connection to the database instance. You establish a connection using the provider's specific connection string.
- Command: Used to execute SQL statements (queries or commands) against the database.
- DataAdapter: Provides a bridge between datasets and database tables. It helps you retrieve data from a database and update it.
- DataReader: A forward-only cursor for reading data retrieved from a database in a row-by-row manner. It's efficient for large datasets.
- DataSet: Represents a disconnected, in-memory cache of data that mirrors a database table or a collection of tables.
Example Program:
Here's a basic C# program that demonstrates connecting to a SQL Server database, reading data from a table, and displaying it on the console:
using System;
using System.Data.SqlClient;
class DatabaseConnectionExample
{
static void Main(string[] args)
{
// Replace with your connection string details
string connectionString = "Server=localhost;Database=MyDatabase;Trusted_Connection=True;";
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // Open the connection
string query = "SELECT * FROM Customers"; // Replace with your query
SqlCommand command = new SqlCommand(query, connection);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetValue(0), reader.GetValue(1));
}
}
}
}
}
catch (SqlException ex)
{
Console.WriteLine("Error connecting to database: {0}", ex.Message);
}
}
}
RETRIEVING DATA FROM DATABASE USING LINQ IN C#
LINQ (Language Integrated Query) provides a declarative and readable way to query data from various sources, including databases.
// This is a conceptual example. A real-world LINQ to SQL or Entity Framework setup is required.
// Assuming a `DataContext` named `db` is available.
var highValueCustomers = from c in db.Customers
where c.TotalSpent > 1000
select new { c.Name, c.Email };
foreach (var customer in highValueCustomers)
{
Console.WriteLine("Name: {0}, Email: {1}", customer.Name, customer.Email);
}
- Advantages of LINQ:
- More readable and maintainable queries compared to raw SQL statements.
- Improved type safety with compile-time checking.
- Integrates seamlessly with C# code for further processing of retrieved data.