0% found this document useful (0 votes)
14 views2 pages

File Hnadling

Csharp

Uploaded by

Hamza Waqas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

File Hnadling

Csharp

Uploaded by

Hamza Waqas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using System;

using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LabTaskFileHandling
{
internal class Program
{
static void Main(string[] args)
{
WriteData();
ReadAndWriteToDatabase();
}

public static void WriteData()


{
FileStream fs = new FileStream("C:\\Users\\ARFA TECH\\Desktop\\
Usama.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
Console.WriteLine("Please enter sentences to write on the file (comma-
separated format: ID,Name,Age):");
string str = Console.ReadLine();
sw.WriteLine(str);
sw.Flush();
sw.Close();
fs.Close();
Console.WriteLine("Data written successfully!");
}

public static void ReadAndWriteToDatabase()


{
string connectionString = "Integrated Security=SSPI;Persist Security
Info=False;Initial Catalog=BiiT;Data Source=DESKTOP-N57UVTA"; ; // Replace with
your database connection string
string filePath = "C:\\Users\\ARFA TECH\\Desktop\\Usama.txt";

try
{
using (FileStream fs = new FileStream(filePath, FileMode.Open,
FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// Split the line by comma
string[] data = line.Split(',');
if (data.Length == 3)
{
int id = int.Parse(data[0]);
string name = data[1];
int age = int.Parse(data[2]);

// Write to database
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO YourTableName (ID,
Name, Age) VALUES (@ID, @Name, @Age)";
using (SqlCommand command = new SqlCommand(query,
connection))
{
command.Parameters.AddWithValue("@ID", id);
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Age", age);
command.ExecuteNonQuery();
}
}
Console.WriteLine($"Data written to database: ID={id},
Name={name}, Age={age}");
}
else
{
Console.WriteLine("Invalid data format. Skipping
line.");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}

Console.ReadKey();
}
}
}

You might also like