我在 c# 中有以下代码片段,其中我正在并行读取文件并在读取然后写回不同位置后替换一些文本。我没有收到任何异常,但文件未写入其他位置
class Program
{
private static readonly object _loc = new object();
public static string FileRead(string fileName)
{
string pattern = @"the";
var result = File.ReadAllText(fileName);
var replacedText = Regex.Replace(result, pattern, "XXXX");
var path = Path.Combine(@"D:\Demo2", fileName);
using (StreamWriter sw = new StreamWriter(path, false))
sw.Write(replacedText);
return replacedText;
}
static void Main(string[] args)
{
var files = Directory.GetFiles(@"D:\Demo", "*.txt");
Parallel.ForEach(files, x =>
{
Console.WriteLine("FileName={0}\tNOC={1}",x, FileRead(x).Length);
});
Console.ReadLine();
}
}