Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
98 lines (76 loc) · 2.69 KB
/
Copy pathProgram.cs
File metadata and controls
98 lines (76 loc) · 2.69 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ReplaceText;
#pragma warning disable IDE0079 // Remove unnecessary suppression
#pragma warning disable IDE0056 // Use index operator
public static class Program
{
public static int Main(params string[] args)
{
var searchOption = SearchOption.TopDirectoryOnly;
if (args is not null && args.Length >= 1 && args[0] == "-r")
{
searchOption = SearchOption.AllDirectories;
args = [.. args.Skip(1)];
}
if (args is null || args.Length < 2 ||
((args.Length & 1) == 0))
{
Console.Error.WriteLine(@"Syntax:
ReplaceText [-r] ""fromtext"" ""totext"" [""fromtext2"" ""totext2"" ...] filepattern");
return -1;
}
var dict = new List<KeyValuePair<string, string>>();
for (int i = 0; i <= args.Length - 3; i += 2)
{
dict.Add(new(args[i], args[i + 1]));
}
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
var namepattern = args[args.Length - 1];
IEnumerable<FileInfo> files;
try
{
var dir = Path.GetDirectoryName(namepattern);
if (string.IsNullOrWhiteSpace(dir))
{
dir = ".";
}
var dirinfo = new DirectoryInfo(dir);
files = dirinfo.EnumerateFiles(Path.GetFileName(namepattern), searchOption);
}
catch (Exception ex)
{
Console.Error.WriteLine($"{namepattern}: {ex.GetBaseException().Message}");
return -1;
}
foreach (var file in files)
{
try
{
var text = File.ReadAllText(file.FullName, encoding);
var newtext = text;
foreach (var item in dict)
{
newtext = newtext.Replace(item.Key, item.Value);
}
if (!ReferenceEquals(newtext, text))
{
Console.WriteLine($"Modifying {file.FullName}");
using var outstream = new StreamWriter(new FileStream(
file.FullName, FileMode.Open, FileAccess.Write, FileShare.Delete), encoding);
outstream.Write(newtext);
outstream.Flush();
outstream.BaseStream.SetLength(outstream.BaseStream.Position);
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"{file}: {ex.GetBaseException().Message}");
}
}
return 0;
}
}