StreamReader and TextReader

I am trying to read from a pbx file using StreamReader, edit the contents and display the contents in a new file using TextReader in C #.

This is my first development task in C #.

I learned java in uni and my new job is using C #.

Basically I have to read the list of entries contained in the pbx file from the telephone system. However, these records contain a line of good call records, followed by a line with several dodgy characters, followed by another line of good records.

My task is to read this file line by line, and then write a piece of code to ignore lines with dodgy characters and output good entries to a new file on my c: \ drive, which ive is called output.txt.

I can write a while loop to pull out dodgy characters, but I'm not sure about the C # code to read from the pbx file on my c drive, and then output the edited content to a new file called output.txt, also on my c.

I am new to C # and have studied Google for many hours. Just need a little guidance, and I'm off ...

+3
source share
1 answer

You didn't mention file encodings, so I stick with UTF-8 settings here.

One option is the β€œregular” loop method, which reads, checks, and conditionally writes, for example:

var inputFilePath  = @"C:\temp\input.txt";
var outputFilePath = @"C:\temp\output.txt";

using (var reader = File.OpenText(inputFilePath))
using (var writer = File.CreateText(outputFilePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        var isValidLine = CheckLine(line);
        if (isValidLine)
        {
            writer.WriteLine(line);
        }
    }
}

VS2008, , , .NET 3.5, 4.0 , ( .NET 3.5 , , ).

var inputFilePath  = @"C:\temp\input.txt";
var outputFilePath = @"C:\temp\output.txt";

var inputLines = File.ReadLines(inputFilePath);

var linesToWrite = inputLines
    .Where(line => IsLineValid(line));

File.WriteAllLines(outputFilePath, linesToWrite);
+4

All Articles