Loading...

OBJECT ORIENTED PROGRAMMING  

>

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:

TYPES OF FILE STREAMS:

C# offers two primary types of file streams:

FileStream:

C#
using (FileStream fileStream = File.OpenRead("myfile.txt"))
{
 // Read data from the file using ReadByte(), ReadBlock(), etc.
}

StreamWriter/StreamReader:

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

File Stream Operations:

Key Considerations:

Exam Style Question:

You are tasked with creating a simple program in C# that reads the contents of a text file and calculates the total number of words in the file. Write the code, including error handling for non-existent files.

Answer Code:

C#
using System;
using System.IO;
public class WordCounter
{
 public static void Main(string[] args)
 {
 if (args.Length != 1)
 {
 Console.WriteLine("Error: Please provide the filename as an argument.");
 return;
 }
 string filePath = args[0];
 int wordCount = 0;
 try
 {
 using (StreamReader reader = new StreamReader(filePath))
 {
 string line;
 while ((line = reader.ReadLine()) != null)
 {
 // Split the line into words using whitespace as delimiter
 string[] words = line.Split(' ', '\t', '\n');
 wordCount += words.Length;
 }
 }
 Console.WriteLine("The file '{0}' contains {1} words.", filePath, wordCount);
 }
 catch (FileNotFoundException)
 {
 Console.WriteLine("Error: File '{0}' not found.", filePath);
 }
 catch (Exception ex)
 {
 Console.WriteLine("An error occurred: {0}", ex.Message);
 }
 }
}

FILE STREAMS IN C#

FileStream Class:

The FileStream class, residing in the System.IO namespace, is the foundation for file I/O operations in C#. It provides a low-level, byte-oriented stream for reading from or writing to files.

Key Points:

Example:

C#
using (FileStream fileStream = File.OpenRead("myfile.txt"))
{
 byte[] buffer = new byte[1024]; // Buffer for reading in chunks
 int bytesRead;
 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
 {
 // Process the read bytes
 }
}

StreamReader Class:

Key Points:

Example:

C#
using (StreamReader reader = new StreamReader("myfile.txt"))
{
 string line;
 while ((line = reader.ReadLine()) != null)
 {
 Console.WriteLine(line); // Read each line of text
 }
}

StreamWriter Class:

Key Points:

Example:

C#
using (StreamWriter writer = new StreamWriter("output.txt"))
{
 writer.WriteLine("Writing text to a file.");
}

Choosing the Right Class:

Remember: Always close file streams using Close() or the using statement to ensure proper resource management.

How to write programs in C# for creating, writing, reading, and appending files:

1. Creating a File:

C#
string filePath = "new_file.txt";
try
{
 // Create a new file
 using (FileStream fileStream = File.Create(filePath))
 {
 Console.WriteLine("File '{0}' created successfully.", filePath);
 }
}
catch (IOException ex)
{
 Console.WriteLine("Error creating file: {0}", ex.Message);
}

2. Writing to a File:

C#
string filePath = "myfile.txt";
string content = "This is some text content.";
try
{
 using (StreamWriter writer = new StreamWriter(filePath))
 {
 writer.WriteLine(content);
 Console.WriteLine("Content written to '{0}'.", filePath);
 }
}
catch (IOException ex)
{
 Console.WriteLine("Error writing to file: {0}", ex.Message);
}

3. Reading from a File:

C#
string filePath = "myfile.txt";
try
{
 using (StreamReader reader = new StreamReader(filePath))
 {
 string line;
 while ((line = reader.ReadLine()) != null)
 {
 Console.WriteLine(line); // Process each line
 }
 }
 Console.WriteLine("Content read from '{0}'.", filePath);
}
catch (IOException ex)
{
 Console.WriteLine("Error reading file: {0}", ex.Message);
}

4. Appending to a File:

C#
string filePath = "myfile.txt";
string contentToAppend = "\nThis is appended content.";
try
{
 using (StreamWriter writer = File.AppendText(filePath))
 {
 writer.WriteLine(contentToAppend);
 Console.WriteLine("Content appended to '{0}'.", filePath);
 }
}
catch (IOException ex)
{
 Console.WriteLine("Error appending to file: {0}", ex.Message);
}

Important Considerations:

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:

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:

C#
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 desired query
 SqlCommand command = new SqlCommand(query, connection);
 using (SqlDataReader reader = command.ExecuteReader())
 {
 if (reader.HasRows)
 {
 // Get column names
 for (int i = 0; i < reader.FieldCount; i++)
 {
 Console.Write(reader.GetName(i) + "\t");
 }
 Console.WriteLine(); // Print a line break
 // Read data row by row
 while (reader.Read())
 {
 for (int i = 0; i < reader.FieldCount; i++)
 {
 Console.Write(reader.GetValue(i) + "\t");
 }
 Console.WriteLine();
 }
 }
 else
 {
 Console.WriteLine("No data found in the table.");
 }
 }
 }
 }
 catch (SqlException ex)
 {
 Console.WriteLine("Error connecting to database: {0}", ex.Message);
 }
 }
}

Remember:

Imagine you have a locked cabinet filled with important documents (your database). ADO.NET in C# acts like a set of tools and instructions to open that cabinet (connect to the database), retrieve specific documents (read data), or even add new ones (write data).

Connecting to the Database

The Cabinet Key (Connection String)

This is a special string containing information about the database, like its location (server address), name, and sometimes even a username and password to unlock it (authentication). Think of it as the key to the cabinet.

Opening the Cabinet (Creating a Connection)

Using the connection string, you create a SqlConnection object in your C# code. This object represents the actual connection you'll use to interact with the database.

Entering the Cabinet (Opening the Connection)

Once you have the SqlConnection object, you call its Open() method. This method "unlocks" the database connection, allowing you to retrieve or store information.

C#
string connectionString = "Server=localhost;Database=MyDatabase;Trusted_Connection=True;"; // Replace with your details
SqlConnection connection = new SqlConnection(connectionString);
connection.Open(); // Open the connection
    

Important! Remember to replace the connectionString with the actual details for your specific database.

Managing the Connection

C#
string connectionString = "Server=localhost;Database=MyDatabase;Trusted_Connection=True;";
using (SqlConnection connection = new SqlConnection(connectionString)) // Connection is automatically closed when the code block ends
{
    connection.Open();
    // Execute your commands here to interact with the database
}
    

Remember: Always handle potential errors (like incorrect connection strings or database access issues) using try...catch blocks to make your code more robust.

Additional Tips

PERFORMING A DATABASE CONNECTION IN ADO.NET (STEP-BY-STEP)

1. Include the Necessary Namespace

C#
using System.Data.SqlClient;
    

2. Define the Connection String

C#
string connectionString = "Server=localhost;Database=MyDatabase;Trusted_Connection=True;";
    

Important! Replace the values with your specific database details.

3. Create a SqlConnection Object

C#
SqlConnection connection = new SqlConnection(connectionString);
    

4. Open the Connection

C#
connection.Open();
    

5. Execute Commands (Optional)

6. Close the Connection (Crucial!)

C#
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Execute your commands here to interact with the database
    // The connection is automatically closed when the code block ends
}
    

The using statement is a convenient way to ensure proper connection management, as it automatically calls Close() when the code block finishes, even if an exception occurs.

7. Handle Errors (Recommended)

C#
try
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // ... your database interaction code ...
    }
}
catch (SqlException ex)
{
    Console.WriteLine("Error connecting to database: {0}", ex.Message);
}
    

Connecting to Microsoft Access Databases

It is also possible to connect to Microsoft Access databases using ADO.NET in C#. However, the process is slightly different compared to connecting to SQL Server because Access uses a different data provider.

1. Data Provider

2. Connection String

3. Code Example

C#
using System.Data.OleDb;
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyDatabase\data.mdb";
try
{
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        connection.Open();
        // ... your database interaction code ...
    }
}
catch (OleDbException ex)
{
    Console.WriteLine("Error connecting to database: {0}", ex.Message);
}
    

Important Notes

Conclusion

Although ADO.NET with the System.Data.OleDb provider allows connecting to Access databases, consider exploring alternative approaches if your project requires advanced features or better performance.

Database Connection Classes in ADO.NET

Using Datasets to Process Database Records

C#
using System.Data.SqlClient;
using System.Data;
// ... connection and command setup
DataSet myDataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(command, connection);
adapter.Fill(myDataSet); // Fill the DataSet with data
// Access and manipulate data within the DataSet (e.g., iterate through rows)
adapter.Update(myDataSet); // Update the database with changes
    

Advantages of Datasets

Disadvantages of Datasets

While Datasets are a core concept in ADO.NET, consider exploring other options like Entity Framework for more complex scenarios and improved data management practices.

RETRIEVING DATA AND DISPLAYING IT IN A DATAGRIDVIEW WITH ADO.NET

Here's an example (assuming you have a table named "Customers" with columns "CustomerID", "Name", and "Email"):

C#
	DataTable dataTable = new DataTable();
	dataTable.Columns.Add("CustomerID", typeof(int)); // Define columns based on your data
	dataTable.Columns.Add("Name", typeof(string));
	dataTable.Columns.Add("Email", typeof(string));
	while (reader.Read())
	{
		int id = reader.GetInt32(0); // Assuming CustomerID is the first column (index 0)
		string name = reader.GetString(1);
		string email = reader.GetString(2);
		DataRow newRow = dataTable.NewRow();
		newRow["CustomerID"] = id;
		newRow["Name"] = name;
		newRow["Email"] = email;
		dataTable.Rows.Add(newRow);
	}
	reader.Close(); // Close the DataReader
	

Here's how to bind the DataTable to the DataGridView:

C#
	dataGridView1.DataSource = dataTable;
	

Complete Example (including connection management and error handling):

C#
	using System.Data.SqlClient;
	using System.Data;
	using System.Windows.Forms; // Assuming a Windows Forms application
	public partial class MyForm : Form
	{
		public MyForm()
		{
			InitializeComponent();
		}
		private void button1_Click(object sender, EventArgs e) // Button click to retrieve data
		{
			string connectionString = "..."; // Replace with your connection string
			try
			{
				using (SqlConnection connection = new SqlConnection(connectionString))
				{
					connection.Open();
					string sql = "SELECT CustomerID, Name, Email FROM Customers";
					SqlCommand command = new SqlCommand(sql, connection);
					using (SqlDataReader reader = command.ExecuteReader())
					{
						DataTable dataTable = new DataTable();
						// ... populate DataTable as explained above ...
						dataGridView1.DataSource = dataTable;
					}
				}
			}
			catch (SqlException ex)
			{
				MessageBox.Show("Error connecting to database: " + ex.Message);
			}
		}
	}
	

ADO.NET allows you to perform Insert, Update, and Delete operations on a database using DataAdapters.

Here's an example (inserting a new customer record):

C#
	string name = "New Customer";
	string email = "newcustomer@email.com";
	// Assuming DataAdapter (adapter) is already configured for the Customers table
	adapter.InsertCommand = new SqlCommand("INSERT INTO Customers (Name, Email) VALUES (@Name, @Email)");
	adapter.InsertCommand.Parameters.AddWithValue("@Name", name);
	adapter.InsertCommand.Parameters.AddWithValue("@Email", email);
	adapter.Update(dataTable); // Update method can handle inserts, updates, and deletes
	

Here's an example (updating an existing customer's email):

C#
	int customerID = 10; // Replace with the ID of the customer to update
	string newEmail = "updated@email.com";
	adapter.UpdateCommand = new SqlCommand("UPDATE Customers SET Email = @NewEmail WHERE CustomerID = @ID");
	adapter.UpdateCommand.Parameters.AddWithValue("@NewEmail", newEmail);
	adapter.UpdateCommand.Parameters.AddWithValue("@ID", customerID);
	adapter.Update(dataTable); // Update method can handle inserts, updates, and deletes
	

Here's an example (deleting a customer by ID):

C#
	int customerID = 10; // Replace with the ID of the customer to delete
	adapter.DeleteCommand = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @ID");
	adapter.DeleteCommand.Parameters.AddWithValue("@ID", customerID);
	adapter.Update(dataTable); // Update method can handle inserts, updates, and deletes
	

RETRIEVING DATA FROM DATABASE USING LINQ IN C#

Here's an example (retrieving all customers from a table):

C#
	string connectionString = "..."; // Replace with your connection string
	using (SqlConnection connection = new SqlConnection(connectionString))
	{
		connection.Open();
		// Define the query expression
		var customers = from customer in connection.OpenReader("SELECT * FROM Customers")
						select customer; // Selects all columns
		// ... process or iterate through the customer data ...
	}
	

Here's an improved example with data access:

C#
	foreach (var customer in customers)
	{
		int id = customer[0]; // Assuming first column is ID (not recommended)
		string name = customer["Name"]; // Accessing by column name (better practice)
		// Process the data for each customer
		Console.WriteLine($"ID: {id}, Name: {name}");
	}
	

End of Outcome Quiz

1 of 20

    Quiz Score

    Percentage: 0%

    Answered Questions: 0

    Correct Answers: 0

    Faults: