Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

c# - reading and editing contents of file

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("
1");
string txt = File.ReadAllText(args[0]);
string[] lines = txt.Split('
');
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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...