• Startseite
  • Tutorials
  • Kontakt
  • Mein Account
Panjutorials
  • Startseite
  • Tutorials
  • Kontakt
  • Mein Account

Writing into a text file in CSharp

In this article, you’ll learn the following: Write a text file in CSharp. This is primarily a way to write text to a file. This can be used to store larger amounts of data and to store them permanently (unlike variables which are removed after closing the program).

Example: Write a text file in CSharp

class Programm
    {


        public static void Main(string[] args)
        {
            // This example assumes that the folder
            // "D: \ Tutorials \ CSharp" is present

            // Example # 1: Write an array of text into a file
            string[] rows = { "First row", "Second row", "Third row" };
            // WriteAllLines creates a file with a collection of strings.
            // The close or flush function must not be called,
            // because WriteAllLines has already done the necessary work.
            System.IO.File.WriteAllLines(@"D:\Tutorials\CSharp\writeText.txt", rows);


            // Example #2: Writing strings to a file
            string text = "My super long and beautiful text, is finally permanently in a "
                + "File.";
        
            System.IO.File.WriteAllText(@"D:\Tutorials\CSharp\writeText2.txt", text);

            // Example # 3: Paste only text when a condition is met
            // With the using statement, we automatically reach the StreamWriter
            // and IDisposable.Dispose is applied to the streamObject.
            // NOTE: Do not use FileStream for text because it writes in bytes, which
            // should be converted back. Streamwriter, on the other hand, encodes directly into text.
            using (System.IO.StreamWriter datei =
                new System.IO.StreamWriter(@"D:\Tutorials\CSharp\writeText3.txt"))
            {
                foreach (string row in rows)
                {
                    // If there is no word "third" in the text, don't write the file.
                    if (!row.Contains("third"))
                    {
                        file.WriteLine(row);
                    }
                }
            }

            // Example #4: Add Text to a file

            using (System.IO.StreamWriter file =
                new System.IO.StreamWriter(@"D:\Tutorials\CSharp\writeText2.txt", true))
            {
                file.WriteLine("More Text");
            }
        }

        // If you execute this code, three files will be created in the named directory.
        // Open it and examine the contents

    }

So you can see, you can choose different ways to save text in a file. You now know how to read files, how to filter them and create your own text files.