读取和编辑文件的内容 [英] reading and editing contents of file

查看:145
本文介绍了读取和编辑文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



AA表示一位或两位数字(每个数字的长度不一定是2),file.txt是文件的名称。我需要一个非常快速的方法来获取文件名。另外,我需要用1替换最后的0。如果文件末尾没有0(可选),我需要在新行添加1。这里是我现在的代码:
$ b $ pre $ StringBuilder sb = new StringBuilder(\r\\\
1);
string txt = File.ReadAllText(args [0]);
string [] lines = txt.Split('\\\
');
string name = lines [4];

if(lines.Length!= 6)//检查EOF是否为0。
txt + = sb.ToString();
else
txt = txt.Substring(0,txt.Length - 1)+'1'; //将0替换为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)//检查EOF是否为0。
lines.Add(1);
else
lines [5] =1;

File.WriteAllLines(args [0],lines);
Console.WriteLine(name);


I have a file which is in this format:

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

Where AA represents a one or two digit number (the length of each doesn't have to be 2), and file.txt is the name of a file. I need a very fast method to obtain the file name. Also, I need to replace the final 0 with 1. If there is no 0 in the file at the end (its optional), I need to append 1 on a new line. Here is my current code:

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);

However, I was wondering if there was even a faster way to do this (without having to load the file in memory maybe). I have to process tons of files like this, so saving tenths would be extremely useful.

解决方案

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);

这篇关于读取和编辑文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆