Выполнить задачу с использованием структуры «текстовый файл» (в файле хранится текст). Создать новый текстовый файл, каждая строка которого содержит последний символ соответствующей строки исходного файла — C#(Си шарп)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
  
var text = @"Выполнить задачу с использованием структуры «текстовый файл» (в файле хранится текст)
  
Создать новый текстовый файл, каждая строка которого содержит последний символ
соответствующей строки исходного файла.";
  
var source = new TextFile("source.txt");
var lines = text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
await source.Create(lines);
  
var destination = new TextFile("destination.txt");
await destination.CreateWithLastSymbols(source.Read());
  
await foreach (var line in destination.Read())
{
    Console.WriteLine(line);
}
  
internal readonly record struct TextFile(string FilePath)
{
    public async Task Create(string[] lines) => await File.WriteAllLinesAsync(FilePath, lines);
  
    public async Task CreateWithLastSymbols(IAsyncEnumerable<string> source)
    {
        await using var stream = new StreamWriter(FilePath, new FileStreamOptions
        {
            Access = FileAccess.Write,
            Mode = FileMode.Create,
            Share = FileShare.None,
            Options = FileOptions.Asynchronous
        });
  
        await foreach (var line in source)
        {
            if (string.IsNullOrEmpty(line))
            {
                await stream.WriteLineAsync(line);
            }
            else
            {
                await stream.WriteLineAsync(line[^1]);
            }
        }
    }
  
    public async IAsyncEnumerable<string> Read()
    {
        using var stream = new StreamReader(FilePath, new FileStreamOptions
        {
            Access = FileAccess.Read,
            Mode = FileMode.Open,
            Share = FileShare.Read,
            Options = FileOptions.Asynchronous | FileOptions.SequentialScan,
        });
  
        while (!stream.EndOfStream)
        {
            yield return await stream.ReadLineAsync();
        }
    }
}

Leave a Comment