C implements the instance code for writing and reading text files

  • 2020-05-12 03:09:11
  • OfStack

Write to text file

class WriteTextFile
    {
        static void Main()
        {
            // If the file does not exist, it is created. Existing covers 
            // This method writes a character array newline display 
            string[] lines = { "first line", "second line", "third line"," The first 4 line " };
            System.IO.File.WriteAllLines(@"C:\testDir\test.txt", lines, Encoding.UTF8);
            // If the file does not exist, it is created. Existing covers 
            string strTest = " The example test 1 Write a string to a text file. ";
            System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8);
            // Process the line of text before writing it to a file 
            //StreamWriter1 Three parameters are overwritten by default 
            //StreamWriter The first 2 The parameters for false Overwrite existing files, as true Appends the text to the end of the file 
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\testDir\test2.txt",true))
            {
                foreach (string line in lines)
                {
                    if (!line.Contains("second"))
                    {
                        file.Write(line);// Append the end of the file directly, no line feed 
                        file.WriteLine(line);//  Directly append the end of the file, line feed    
                    }
                }
            }
        }
    }

Read text file

class ReadTextFile
    {
        static void Main()
        {
            // Read the string directly 
            string text = System.IO.File.ReadAllText(@"C:\testDir\test1.txt");
            Console.WriteLine(text);
            // Reads as an array of strings by line 
            string[] lines = System.IO.File.ReadAllLines(@"C:\testDir\test.txt");
            foreach (string line in lines)
            {
                Console.WriteLine(line);
            }
            // Read the text file as a stream from beginning to end 
            // This method will 1 line 1 Line read text 
            using (System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\testDir\test.txt"))
            {
                string str;
                while ((str = sr.ReadLine()) != null)
                {
                    Console.WriteLine(str);
                }
            }
            Console.Read();
        }
    }


Related articles: