C # reads text data block (the FileStream)

C # reads text data block (the FileStream)

January 5, 2013 15:16:21  xs_zgsc  Reads 4118

For a lot of text when the block to process data.

Directly on the code:

 

 
  1. using System.IO;

  2. using System.Text;

  3.  
  4. static void ReadStreamFromFile()

  5. {

  6. string filePath = @"D:\test.txt";

  7. int bufferSize = 1024; //每次读取的字节数

  8. byte[] buffer = new byte[bufferSize];

  9. FileStream stream = null;

  10. try

  11. {

  12. stream = new FileStream(filePath, FileMode.Open);

  13. long fileLength = stream.Length;//文件流的长度

  14. int readCount = (int)Math.Ceiling((double)(fileLength / bufferSize)); //需要对文件读取的次数

  15. int tempCount = 0;//当前已经读取的次数

  16. do

  17. {

  18. stream.Read(buffer, tempCount * bufferSize, bufferSize); //分readCount次读取这个文件流,每次从上次读取的结束位置开始读取bufferSize个字节

  19. //这里加入接收和处理数据的逻辑-

  20. string str = Encoding.Default.GetString(buffer);

  21. Console.WriteLine(str);

  22. tempCount++;

  23. }

  24. while (tempCount < readCount);

  25. }

  26. catch

  27. {

  28. }

  29. finally

  30. {

  31. if (stream != null)

  32. stream.Dispose();

  33. }

  34. }

 

among them:

stream.Read(buffer, tempCount * bufferSize, bufferSize)

 

Read actually used to read block segment, a counter is used to identify tempCount where the read section, and then continues to read the data length defined from this location down from bufferSize

 If text data is not large, the method can also be used directly StreamReader start to end.

code show as below:

 

 
  1. string FileName = Server.MapPath("Test.txt");

  2. string TxtContent = "";

  3. if (File.Exists(FileName))

  4. {

  5. StreamReader objReader = new StreamReader(FileName, System.Text.Encoding.GetEncoding("gb2312"));

  6. while (!objReader.EndOfStream)

  7. {

  8. TxtContent += objReader.ReadLine() + ",";

  9. }

  10. objReader.Close();

  11. }

  12.  
  13. string[] strArr = TxtContent.Split(',');

  14.  
  15. for (int i = 0; i < strArr.Length; i++)

  16. {

  17. Response.Write(strArr[i] + " ");

  18. if ((i + 1) % 6 == 0)

  19. {

  20. Response.Write("<br>");

  21. }

  22. }

Guess you like

Origin blog.csdn.net/cxu123321/article/details/92990570