c# – 读取和写入文本文件时出现意外输出

我对C#中的文件有点新,我遇到了问题.从文件读取并复制到另一个文件时,最后一块文本没有被写入.以下是我的代码:

StringBuilder sb = new StringBuilder(8192);
string fileName = "C:...rest of path...inputFile.txt";
string outputFile = "C:...rest of path...outputFile.txt";

using (StreamReader reader = File.OpenText(fileName))
{
   char[] buffer = new char[8192];
   while ((reader.ReadBlock(buffer, 0, buffer.Length)) != 0)
   {
      foreach (char c in buffer)
      {
         //do some function on char c... 
         sb.Append(c);
      }

      using (StreamWriter writer = File.CreateText(outputFile))
      {
         writer.Write(sb.ToString());
      }
   }
}

我的目标是以缓冲方式读取和写入文本文件.我将通过以下方式实现Java中的某些功能:

public void encrypt(File inputFile, File outputFile) throws IOException
{
   BufferedReader infromfile = null;
   BufferedWriter outtofile = null;

   try
   {
      String key = getKeyfromFile(keyFile);
      if (key != null)
      {
         infromfile = new BufferedReader(new FileReader(inputFile));
         outtofile = new BufferedWriter(new FileWriter(outputFile));
         char[] buffer = new char[8192];
         while ((infromfile.read(buffer, 0, buffer.length)) != -1)
         {
            String temptext = String.valueOf(buffer);
            //some changes to temptext are done
            outtofile.write(temptext);
         }
      }
   }
   catch (FileNotFoundException exc)
   {
   } // and all other possible exceptions
}

你能帮我找出问题的根源吗?

如果您认为可能有更好的方法来实现带有文本文件的缓冲i / o,我将非常感谢您的建议.

最佳答案 有几个“陷阱”:

> c无法更改(它是foreach迭代变量),您需要复制它才能在写入之前进行处理
>你必须跟踪缓冲区的大小,ReadBlock用字符填充它会使你的输出变脏

像这样更改代码看起来像是有效的:

//extracted from your code
foreach (char c in buffer)
{
    if (c == (char)0) break; //GOTCHA #2: maybe you don't want NULL (ascii 0) characters in your output

    char d = c; //GOTCHA #1: you can't change 'c'

    // d = SomeProcessingHere();

    sb.Append(d);
}
点赞