Answer on question #70289, Programming & Computer Science / C#
Q: How would I use stream reader to read a text file from user input (which was stream writer)?
enter 3 param. :
1: fffffffffffffffff
2: dddddddd
3: ss
Received lines from a file:
line1: 1: fffffffffffffffff
line2: 2: dddddddd
line3: 3: ss
Only entered value from line:
param1: fffffffffffffffff
param2: dddddddd
param3: ss
1Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] arr_str;
// Create file
string path = @"D:\new_file.txt";
FileInfo MyFile = new FileInfo(path);
FileStream fs = MyFile.Create();
fs.Close();
// Getting param
Console.WriteLine("Enter 3 param. : ");
Console.Write("1: ");
string param1 = Console.ReadLine();
Console.Write("2: ");
string param2 = Console.ReadLine();
Console.Write("3: ");
string param3 = Console.ReadLine();
// Write data in file
try
{
using (StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default))
{
sw.WriteLine("1: " + param1);
sw.WriteLine("2: " + param2);
sw.WriteLine("3: " + param3);
sw.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// Get data from file in array
try
{
string str = "";
int ind = 0;
using (StreamReader sr = new StreamReader(path))
{
while (sr.ReadLine() != null)
{
ind++;
}
sr.Close();
}
arr_str = new string[ind];
ind = 0;
using (StreamReader sr = new StreamReader(path))
{
while ((str = sr.ReadLine()) != null)
{
arr_str[ind] = str;
ind++;
}
sr.Close();
}
// Write line from file
Console.WriteLine();
Console.WriteLine("Received lines from a file:");
Console.WriteLine("line1: " + arr_str[0]);
Console.WriteLine("line2: " + arr_str[1]);
Console.WriteLine("line3: " + arr_str[2]);
// Delete start symbol
for (int i = 0; i < arr_str.Length; i++)
{
arr_str[i] = arr_str[i].Substring(arr_str[i].LastIndexOf(@": ") + 1);
}
param1 = arr_str[0];
param2 = arr_str[1];
param3 = arr_str[2];
// Write only entered value
Console.WriteLine();
Console.WriteLine("Only entered value from line:");
Console.WriteLine("param1: " + arr_str[0]);
Console.WriteLine("param2: " + arr_str[1]);
Console.WriteLine("param3: " + arr_str[2]);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
}Answer provided by www.AssignmentExpert.com
Comments