1. Odd Lines- Lab: Streams, Files and Directories
Здравейте,
опитвам се да реша първата задача от Лаба, но не със стриймове, както трейнъра показва, а чрез използването на класа File. Искам максимално добре да се науча да се възползвам от готовите функционалностти на езика, защото съм убедена, че свободното време на програмиста е оскъдно и ценно.
Условие- https://softuni.bg/trainings/resources/officedocument/52727/streams-files-and-directories-lab-csharp-advanced-september-2020/3007
Write a program that reads a text file and writes it's every odd line in another file. Line numbers starts from 0.
Имам създадени нови два текстови файла и са точно там където се стартира програмата (при .exe fail), като успявам да чета информация от единия, но не и да презапиша нечетните редове в другия файл. Втория файл си остава празен.
Моля за помощ!
using System;
using System.IO;
namespace OddLines
{
class Program
{
static void Main(string[] args)
{
string[] text = File.ReadAllLines("OddLines.txt");
for (int i = 0; i < text.Length; i++)
{
if (i % 2 != 2)
{
File.WriteAllText("OddLinesAnother.txt",text[i]);
}
}
}
}
}
Thanks a lot to both of you!
In the first case with "File" my mistake is- "i%2!=2" (with i%2!=0 is not working too), but in the second case with StreamRider and StreamWriter, I used to i%2==1 for odd lines and is not working too.
I did everything from the video step by step, but without any result.
I will try Axiomatik's solution with absolute path.
In another forum somebody said that my logic with StreamReader and StreamWriter is correct, but maybe the problem is in my input file with too much spaces and new lines, and the program skiped the logic. Is that possible?
if Axiomatic's solution doesn't work on my PC I would unistal my Office packages and install different version.
Yes, is working correctly with my new Notepad++ and absolute path.
@Axiomatik
thank you so much!
using System;
using System.IO;
namespace OddLines
{
class Program
{
static void Main(string[] args)
{
using (var reader = new StreamReader(@"C:\Users\eli\Desktop\AllMyRepos\CSharp-Advanced\StreamsFilesAndDirectories-Lab\OddLines\input.txt"))
{
using (var writer = new StreamWriter(@"C:\Users\eli\Desktop\AllMyRepos\CSharp-Advanced\StreamsFilesAndDirectories-Lab\OddLines\output.txt"))
{
int counter = 0;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (counter % 2 == 1)
{
writer.WriteLine(line);
}
counter++;
}
}
}
}
}
}
Super, but it should also work with VS.
Best,