A
A
Alukar2014-08-06 12:52:58
C++ / C#
Alukar, 2014-08-06 12:52:58

How to add a line at the end of a file in C#?

We urgently need to make a small application on our knees, unfortunately there is very little knowledge of C#.

string[] file = File.ReadAllLines(folder+"\\file.txt", Encoding.Default);
string result = file[1].Substring(1, file[1].Length - 1);
file[1] = file[1].Remove(1) + "MyText";
File.WriteAllLines(folder+"\\file.txt", file, Encoding.Default);

I just managed to add to the right place in the file, but how to determine the number of lines and add a new line "MyText2" to the end?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tsiren Naimanov, 2014-08-06
@Alukar

Everything from MSDN

string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                File.WriteAllLines(folder+"\\file.txt", file, Encoding.Default);
                sw.WriteLine(MyText2);
                sw.WriteLine(MyText3);
            }
        }

// Open the file to read from.
        int I = 0;
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                I++;
            }
       label1.Text = Convert.ToString(I);
и всё в лебеле у тебя кол-во строк - непустых
        }

I hope you understand the meaning)

A
Alukar, 2014-08-06
@Alukar

That's how I crabbed it , it works ...

var lines = File.ReadAllLines(path);
                    var count = lines.Length - 1;
                    string[] file = File.ReadAllLines(path, Encoding.Default);
                    string result = file[count].Substring(file[count].Length);
                    file[count] = Settings.Default.realmlist;
                    File.WriteAllLines(path, file, Encoding.Default);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question