20. FileStream yordamida matnli faylga ma'lumotlarni o'qish va yozish uchun C# dasturini amalga oshiring.
Javob:
using System.IO;
class Program {
static void Main(string[] args) {
// Path to text file
string path = @"C:\example.txt";
// Write data to text file
using (FileStream fs = new FileStream(path, FileMode.Create)) {
using (StreamWriter writer = new StreamWriter(fs)) {
// Data to be written
string data = "Hello, World!";
writer.Write(data);
}
}
// Read data from text file
using (FileStream fs = new FileStream(path, FileMode.Open)) {
using (StreamReader reader = new StreamReader(fs)) {
// Output read data (Hello, World!)
System.Console.WriteLine(reader.ReadToEnd());
}
}
}
}
Izoh: Bu kod “Salom, dunyo!” matnini yozadi. C:\example.txt manzilida joylashgan matn fayliga, so‘ngra uni qayta o‘qiydi va konsolda chop etadi.
21. C# da CSV faylini yozish uchun StreamWriter-dan foydalaning.
Javob:
using System.IO;
// Define the file path and name
string filePath = "example.csv";
// Create the StreamWriter object
StreamWriter sw = new StreamWriter(filePath);
// Write the headers to the CSV file
sw.WriteLine("Name, Age, Occupation");
// Write some data to the CSV file
sw.WriteLine("John, 35, Engineer");
sw.WriteLine("Sarah, 28, Teacher");
sw.WriteLine("David, 42, Accountant");
// Close the StreamWriter object
sw.Close();
Ushbu misol C# ilovasi bilan bir xil katalogda "example.csv" nomli faylni yaratadi va unga bir nechta namuna ma'lumotlarini yozadi. Maʼlumotlarni ehtiyojlaringizga mos ravishda oʻzgartirishingiz mumkin.
22. FileStream yordamida XML fayliga ma'lumotlarni o'qish va yozish uchun C# dasturini yozing.
Javob:
using System;
using System.IO;
using System.Xml;
class Program
{
static void Main()
{
string filePath = "example.xml";
XmlDocument doc = new XmlDocument();
// Check if the XML file exists
if (File.Exists(filePath))
{
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
// Load the existing XML file
doc.Load(fs);
}
}
else
{
// Create a new root node
XmlNode rootNode = doc.CreateElement("RootNode");
doc.AppendChild(rootNode);
}
// Add some data to the XML file
XmlNode newNode = doc.CreateElement("DataNode");
XmlAttribute attribute = doc.CreateAttribute("name");
attribute.Value = "John";
newNode.Attributes.Append(attribute);
newNode.InnerText = "35";
doc.DocumentElement.AppendChild(newNode);
// Save the changes to the XML file
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
doc.Save(fs);
}
Console.WriteLine("Data written to XML file.");
}
}
Ushbu dastur misolida biz birinchi navbatda XML fayli mavjudligini tekshiramiz. Agar shunday bo'lsa, biz mavjud faylni FileStream yordamida yuklaymiz. Aks holda, biz XML hujjati uchun yangi ildiz tugunini yaratamiz
Do'stlaringiz bilan baham: |