user1848210 user1848210 - 1 month ago 13
C# Question

Open txt file and replace text in the first two lines (C#)

I am writing this program that allows me to generate txt files that with an incremental number, however, i want each file serial number to be writting inside the txt file itself.

For example:
I generated 3 files, Mytext-000001.txt, Mytext-000002.txt, Mytext-000003.txt, and each file first line contains "Hello 000000" and the second line contains "My number is 000000", now i want to change each txt file to contain "Hello " + the incremental number that it is named with.

So the output of each file will be:

Mytext-000001.txt,
Hello 000001
My number is 000001

Mytext-000002.txt,
Hello 000002
My number is 000002


Mytext-000003.txt,
Hello 000002
My number is 000003


My Code

string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + @"\path.txt";
string pth_input = null;
string pth_output = null;

using (StreamReader sx = File.OpenText(path))
{
pth_input = sx.ReadLine();
pth_output = sx.ReadLine();
}


Console.WriteLine("Number of Files?");
string number_of_files = Console.ReadLine();
int get_number_of_files = Int32.Parse(number_of_files) + 1;

string PathFiletoCopy = pth_input;
string Extension = System.IO.Path.GetExtension(PathFiletoCopy);
string PartialNewPathFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(PathFiletoCopy), System.IO.Path.GetFileNameWithoutExtension(PathFiletoCopy) + "-");

for (int i = 1; i < get_number_of_files; i++)
{
System.IO.File.Copy(PathFiletoCopy, PartialNewPathFile + i.ToString("D6") + Extension);
}
string[] txtfiles = Directory.GetFiles(pth_output, "*.txt");
foreach (var file in txtfiles)
{
string get_file_counter = System.IO.Path.GetDirectoryName(file.Substring(7,6));
FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write);
FileStream fi = new FileStream(file, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fi))
{
using (StreamWriter writer = new StreamWriter(fs))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{

string replace_line_one = line.Replace("Hello 000001","Hello"+ "["+get_file_counter+"]");
string replace_line_two = line.Replace("My number is 000001", "My number is" + "[" + get_file_counter + "]");

}
writer.Close();
} reader.Close();

}
}
Console.Read();


I hope you can help

Appreciate your help guys

Answer
string[] files = Directory.GetFiles(directoryPath, "*.txt");
Regex regex = new Regex("\\d+(?=\\.txt)");

foreach (var file in files)
{
    string[] lines = File.ReadAllLines(file);
    string number = regex.Match(Path.GetFileName(file)).Value;

    lines[0] = "Hello " + number;
    lines[1] = "My number is " + number;

    File.WriteAllLines(file, lines);
}

Regex makes this solution nonspecific.

Comments