Buka file yang ada, tambahkan satu baris

261

Saya ingin membuka file teks, menambahkan satu baris ke sana, lalu tutup.

Blankman
sumber

Jawaban:

357

Anda dapat menggunakannya File.AppendAllTextuntuk itu:

File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
Fredrik Mörk
sumber
122
using (StreamWriter w = File.AppendText("myFile.txt"))
{
  w.WriteLine("hello");
}
Gabe
sumber
2
Ini adalah cara yang tepat untuk menulis ke file adalah Anda menghasilkan banyak baris, untuk menghindari masalah memori.
Oscar Fraxedas 6-18
81

Satu pilihan! Tapi yang pertama sangat sederhana. Utilitas terakhir mungkin untuk manipulasi file:

//Method 1 (I like this)
File.AppendAllLines(
    "FileAppendAllLines.txt", 
    new string[] { "line1", "line2", "line3" });

//Method 2
File.AppendAllText(
    "FileAppendAllText.txt",
    "line1" + Environment.NewLine +
    "line2" + Environment.NewLine +
    "line3" + Environment.NewLine);

//Method 3
using (StreamWriter stream = File.AppendText("FileAppendText.txt"))
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

//Method 4
using (StreamWriter stream = new StreamWriter("StreamWriter.txt", true))
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

//Method 5
using (StreamWriter stream = new FileInfo("FileInfo.txt").AppendText())
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}
Sergio Cabral
sumber
5

Mungkin ingin memeriksa kelas TextWriter .

//Open File
TextWriter tw = new StreamWriter("file.txt");

//Write to file
tw.WriteLine("test info");

//Close File
tw.Close();
Robert Greiner
sumber
2

File.AppendText akan melakukannya:

using (StreamWriter w = File.AppendText("textFile.txt")) 
{
    w.WriteLine ("-------HURRAY----------");
    w.Flush();
}
Robben_Ford_Fan_boy
sumber
2

Cara terbaik secara teknis mungkin ini di sini:

private static async Task AppendLineToFileAsync([NotNull] string path, string line)
{
    if (string.IsNullOrWhiteSpace(path)) 
        throw new ArgumentOutOfRangeException(nameof(path), path, "Was null or whitepsace.");

    if (!File.Exists(path)) 
        throw new FileNotFoundException("File not found.", nameof(path));

    using (var file = File.Open(path, FileMode.Append, FileAccess.Write))
    using (var writer = new StreamWriter(file))
    {
        await writer.WriteLineAsync(line);
        await writer.FlushAsync();
    }
}
MovGP0
sumber
1
Satu-satunya pilihan untuk tidak melempar kesalahan jika dipanggil secara berurutan
Alien Technology
0
//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
   stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
   stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
   stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
   stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}
raja Kabil
sumber
0

Kita bisa menggunakan

public StreamWriter(string path, bool append);

saat membuka file

string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);

Parameter pertama adalah string untuk menahan path file lengkap. Parameter kedua adalah Append Mode, yang dalam hal ini dibuat benar

Menulis ke file dapat dilakukan dengan:

writer.Write(string)

atau

writer.WriteLine(string)

Kode sampel

private void WriteAndAppend()
{
            string Path = Application.StartupPath + "\\notes.txt";
            FileInfo fi = new FileInfo(Path);
            StreamWriter SW;
            StreamReader SR;
            if (fi.Exists)
            {
                SR = new StreamReader(Path);
                string Line = "";
                while (!SR.EndOfStream) // Till the last line
                {
                    Line = SR.ReadLine();
                }
                SR.Close();
                int x = 0;
                if (Line.Trim().Length <= 0)
                {
                    x = 0;
                }
                else
                {
                    x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
                }
                x++;
                SW = new StreamWriter(Path, true);
                SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine(x.ToString() + "." + textBox1.Text);

            }
            else
            {
                SW = new StreamWriter(Path);
                SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine("1." + textBox1.Text);
            }
            SW.Flush();
            SW.Close();
        }
Dennis
sumber