Replace using Script in C#

2019-09-05 22:04发布

问题:

How can i read a certain portion of a text file and replace with another line?

Like in the file there is a part :"Attend_10" want to replace it with "Attend_10_[Variable_Value].

How can i Do this using script (C#) in SSIS?

回答1:

I'm not sure exactly what your inputs are, or requirements for matching, but you could easily use Linq or a for loop to perform this. Below are two simple examples that read an input file sample.txt and write to an output file out.csv.

Using Linq:

string periodValue = "201410";
File.WriteAllLines(
    "out.txt",
    File.ReadAllLines("sample.txt").
        Select(l => l.Replace("Attend_10", "Attend_10_" + periodValue))
    );

Using a for loop:

string periodValue = "201410";
string[] lines = File.ReadAllLines("sample.txt");
for (int i = 0; i < lines.Length; i++)
{
    lines[i] = lines[i].Replace("Attend_10", "Attend_10_" + periodValue);
}
File.WriteAllLines("out.txt", lines);

Input: sample.txt:

<SomeTextHere>
<File Name>=Attend_10
<MoreTextHere>

Output: out.txt

<SomeTextHere>
<File Name>=Attend_10_201410
<MoreTextHere>

If your matching requirements are more advanced, you can use RegEx to match certain patterns in each string.



标签: c# ssis c#-3.0