读取和编辑文件的内容

本文关键字:编辑文件 读取 | 更新日期: 2023-09-27 18:18:46

我有一个文件,格式为:

AA
AA AA AA
AA AA AA AA AA AA
AA AA AA
file.txt
0

其中AA表示一个或两个数字(每个数字的长度不一定是2),file.txt是文件名。我需要一个非常快的方法来获取文件名。同时,我需要把最后的0替换成1。如果文件末尾没有0(这是可选的),我需要在新行追加1。下面是我当前的代码:

StringBuilder sb = new StringBuilder("'r'n1");
string txt = File.ReadAllText(args[0]);
string[] lines = txt.Split(''n');
string name = lines[4];
if (lines.Length != 6) // Check if EOF is 0 or not.
    txt += sb.ToString();
else
    txt = txt.Substring(0, txt.Length - 1) + '1'; // Replace 0 with 1.
File.WriteAllText(args[0], txt);
Console.WriteLine(name);

然而,我想知道是否有更快的方法来做到这一点(也许不必在内存中加载文件)。我必须处理像这样的大量文件,所以节省十分之一将非常有用。

读取和编辑文件的内容

var lines = new List<string>(File.ReadAllLines(args[0]));
string name = lines[4];
if (lines.Length != 6) // Check if EOF is 0 or not.
    lines.Add("1");
else
    lines[5] = "1";
File.WriteAllLines(args[0], lines);
Console.WriteLine(name);

如果文件大小低于min(MemoryPageSize, FSBlockSize),通常为4K,则将整个文件加载到内存中可能是您最快的选择

所以假设你有一个字符串文件的内容,我认为使用像

这样的东西
int n;
if (content.EndsWith("'r'n0")
{
  n=content.Length-3;
  content=content.Substring(0,n+2)+"1";
}
else
{
  n=content.Length;
  content=content+"'r'n1";
}

并将字符串写入文件。这将为您节省相当昂贵的Split()

作为文件名,我们继续如下:

int p=content.LastIndexOf(''n',n);
String filename=content.Substring(p+1,n-p);

如果您正在寻找速度,那么您希望使用FileStream。读到临时缓冲区。下面是我整理的一些东西,可能会帮助你指向一个稍微不同但更快的方向:

StringBuilder filename = new StringBuilder();
using (FileStream stream = new FileStream(args[0], FileMode.Open, FileAccess.Read))
{
    byte[] buffer = new byte[1];
    while (stream.Read(buffer, 0, 1) > 0)
    {
        char c = (char) buffer[0];
        if (char.IsLetter(c) || char.IsPunctuation(c))
            filename.Append(c);
    }
}