C reads and writes multiple method instance codes in the txt file

  • 2020-05-26 09:59:49
  • OfStack

1. Add a namespace


System.IO;
System.Text;

2. File reading

(1). Use FileStream class to read the file, and convert it into char array, and then output.


byte[] byData = new byte[100];
        char[] charData = new char[1000];
        public void Read()
        {
            try
            {
                FileStream file = new FileStream("E:\\test.txt", FileMode.Open);
                file.Seek(0, SeekOrigin.Begin);
                file.Read(byData, 0, 100); //byData Array of bytes passed in , To accept FileStream Data in an object , The first 2 Two parameters are the position in the byte array where the data is started to be written , It is usually 0, Represents writing data to an array from the beginning file of the array , The last 1 Specifies how many characters to read from the file .
                Decoder d = Encoding.Default.GetDecoder();
                d.GetChars(byData, 0, byData.Length, charData, 0);
                Console.WriteLine(charData);
                file.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
            }
        }

(2). Use StreamReader to read the file, and then output 1 line and 1 line.


public void Read(string path)
        {
            StreamReader sr = new StreamReader(path,Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null) 
            {
                Console.WriteLine(line.ToString());
            }
        }

3. Write files

(1). Use the FileStream class to create a file and then write the data to the file.


public void Write()
        {
            FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
            // Get the byte array 
            byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!"); 
            // Began to write 
            fs.Write(data, 0, data.Length);
            // Empty the buffer and close the stream 
            fs.Flush();
            fs.Close();
        }

(2). Use the FileStream class to create files, and use the StreamWriter class to write data to files.


public void Write(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            // Began to write 
            sw.Write("Hello World!!!!");
            // Empty buffer 
            sw.Flush();
            // Close the stream 
            sw.Close();
            fs.Close();
        }


Related articles: