快速更改txt文件并保存它的方法

use*_*884 6 c# asp.net

我有txt文件(65mb)我需要逐行读取并更改每一行,例如我有很多行

User=value Password=value  Phone=123456789
User=value Password=value  Phone=123456789
User=value Password=value  Phone=123456789
Run Code Online (Sandbox Code Playgroud)

我需要将第一个信用卡/手机号码更改为*(安全原因),并获取此类文本并将其保存,或者只是为了显示原始文本文件.

User=value Password=value  Phone=*****6789
User=value Password=value  Phone=*****6789
User=value Password=value  Phone=*****6789
Run Code Online (Sandbox Code Playgroud)

我构建了新的字符串并添加到行(更改)行而不是保存,但它花了我很多时间这是我的代码

 string NewPath = "";
        string lineOfText;
        string NewTextFile = "";
        using (var filestream = new FileStream(FilePath,
                             FileMode.Open,
                             FileAccess.Read,
                             FileShare.ReadWrite))
        {
            var file = new StreamReader(filestream, Encoding.UTF8, true, 128);

            while ((lineOfText = file.ReadLine()) != null)//here i reading line by line
            {
                NewTextFile += lineOfText.Substring(0, 124) + "************" +
                lineOfText.Substring(136, lineOfText.Length - 136);
                NewTextFile += Environment.NewLine;//here i make new string
            }
        }

        NewPath = FilePatharr[1] + "\\temp.txt";
        System.IO.File.WriteAllText(NewPath, NewTextFile);//here i save him
Run Code Online (Sandbox Code Playgroud)

任何人都知道更好的方法来做到这一点,我的代码需要很长时间来保存这个大文件.
UPDATE

为什么我为这个问题得到-2?关于这个问题的问题.我在这里只看到关于如何传递敏感数据的错误答案以及更多不属于这个问题的事情当问题是 - >快速改变txt文件的方法并保存

无论如何我发现如何将这个savig文件speedUp的速度从100kb\sec提高到3MB\sec现在它需要20秒而不是像之前的20分钟

Jim*_*hel 3

这里的主要问题是要附加到字符串。这很快就会变得昂贵。您应该能够在大约五秒钟内处理这 65 MB。这就是我要做的:

string outputFileName = "temp.txt";
using (var outputFile = new StreamWriter(outputFileName))
{
    foreach (var line in File.ReadLines(inputFileName))
    {
        var newLine = line.Substring(0, 124) + "************" +
                    line.Substring(136, lineOfText.Length - 136);
        outputFile.WriteLine(newLine);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将比附加字符串快得多。如果您确实想在内存中完成所有操作,请使用StringBuilder. 代替

string NewTextFile = "";
Run Code Online (Sandbox Code Playgroud)

使用

StringBuilder NewTextFile = new StringBuilder();
Run Code Online (Sandbox Code Playgroud)

当您编写输出时,将字符串连接替换为:

NewTextFile.AppendLine(
    lineOfText.Substring(0, 124) + "************" +
    lineOfText.Substring(136, lineOfText.Length - 136));
Run Code Online (Sandbox Code Playgroud)

最后,将其写入文件:

System.IO.File.WriteAllText(NewPath, NewTextFile.ToString());
Run Code Online (Sandbox Code Playgroud)