SoFunction
Updated on 2025-03-07

C# implements the example code for writing and reading text files


class WriteTextFile
    {
        static void Main()
        {
//If the file does not exist, create it; if it exists, it will be overwritten
//This method writes character array to display newline
string[] lines = { "first line", "second line", "third line", "fourth line" };
            (@"C:\testDir\", lines, Encoding.UTF8);
//If the file does not exist, create it; if it exists, it will be overwritten
string strTest = "This example tests a string to be written to a text file.";
            (@"C:\testDir\", strTest, Encoding.UTF8);
// Process text lines before writing text to file
//StreamWriter one parameter is overridden by default
//The second parameter of StreamWriter is false to overwrite the existing file. If true, the text will be appended to the end of the file.
            using ( file = new (@"C:\testDir\",true))
            {
                foreach (string line in lines)
                {
                    if (!("second"))
                    {
(line);//Add the end of the file directly without changing the line
(line);// Append directly to the end of the file and line break
                    }
                }
            }
        }
    }