Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...