Reputation: 872
static void Main(string[] args)
{
FileInfo fileInfo = new FileInfo("C:\\Users\\Alameer Ashraf\\Desktop\\data binding and I Ostreaming\\ResultFile.txt");
using (StreamWriter writer = fileInfo.CreateText())
{
FileInfo Teto = new FileInfo("C:\\Users\\Alameer Ashraf\\Desktop\\data binding and I Ostreaming\\WorkerTable.txt");
foreach (string line in File.ReadLines("C:\\Users\\Alameer Ashraf\\Desktop\\data binding and I Ostreaming\\WorkerTable.txt"))
{
string[] columns = line.Split(',');
Console.WriteLine("<Name>");
Console.WriteLine(columns[0]);
Console.WriteLine("<" + "/" + "Name" + ">");
Console.WriteLine("<ID >");
Console.WriteLine(columns[1]);
Console.WriteLine("<" + "/" + "ID " + ">");
Console.WriteLine("<Number>");
Console.WriteLine(columns[2]);
Console.WriteLine("<" + "/" + "Number " + ">");
Console.WriteLine("<Job>");
Console.WriteLine(columns[3]);
Console.WriteLine("<" + "/" + "Job " + ">");
}
Console.ReadLine();
}
i failed to do what i have been explained ?? help please i want to read from a file , then write what i'm reading into another one by using the same application , can i do that ? i want to read an .csv file and extract information from , then rewriting that information into another text file in the same console application , using IO File stream .
Upvotes: 1
Views: 2839
Reputation: 6088
The following code will do what you want:
class Program
{
static void Main(string[] args)
{
using(StreamReader reader = new StreamReader(File.OpenRead("C:\\Users\\Alameer Ashraf\\Desktop\\data binding and I Ostreaming\\WorkerTable.txt")))
{
using (StreamWriter writer = new StreamWriter(File.Open ("C:\\Users\\Alameer Ashraf\\Desktop\\data binding and I Ostreaming\\ResultFile.txt", FileMode.Create)))
{
string line;
while((line = reader.ReadLine()) != null) {
string[] columns = line.Split(',');
WriteAndPrint(writer, "<Name>");
WriteAndPrint(writer, columns[0]);
WriteAndPrint(writer, "</Name>");
WriteAndPrint(writer, "<ID >");
WriteAndPrint(writer, columns[1]);
WriteAndPrint(writer, "</ID >");
WriteAndPrint(writer, "<Number>");
WriteAndPrint(writer, columns[2]);
WriteAndPrint(writer, "</Number>");
WriteAndPrint(writer, "<Job>");
WriteAndPrint(writer, columns[3]);
WriteAndPrint(writer, "</Job>");
}
}
}
Console.ReadLine();
}
static void WriteAndPrint(StreamWriter writer, string line)
{
Console.WriteLine(line);
writer.WriteLine(line);
}
}
Although, I cringe at seeing what seems to be XML written directly to a file when a perfectly good library for interfacing with XML data exists in .NET. You should also probably look for a proper CSV parser, or write one yourself; it's not a very difficult specification to match.
Upvotes: 2