我的File.txt包含
123456781
123456781
我的NewFile应该包含
123456782
123456782
步骤1:将内容从旧文件复制到新文件
StreamReader reader = File.OpenText(@"C:\File.txt");
using (Stream file = File.Create("NewFile.txt"))
{
CopyStream(reader.BaseStream, file);
}
private void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
第2步:在这里遇到问题。
StreamReader reader = File.OpenText("NewFile.txt");
while (!reader.EndOfStream)
{
string currentLine = reader.ReadLine();
//Logic to increment the number is written
//Now saving the change to the file...
if (reader!=null && reader.ReadLine() != null)
{
//contents is the file content with the changed numbers
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
MemoryStream myStream = new MemoryStream(byteArray);
File.AppendAllText("New.txt", contents); //Here is the issue
}
}
我无法保存它。如何保存运行时,如果我指定新文件名,我不会同时保存这两行。
File.AppendAllText("New2.txt", contents);
答案 0 :(得分:3)
请注意,在while
循环内,您的代码连续执行了两次reader.ReadLine()
。
您的代码第一次从“NewFile.txt”中读取一行到变量 currentLine :
string currentLine = reader.ReadLine();
然后在它之后读取读者的下一行:
if (reader!=null && reader.ReadLine() != null)
但它不会在任何地方从文件中读取第二行。
这意味着,您的while
循环会丢弃“NewFile.txt”中的每一行。 (如果“NewFile.txt”只包含一行,则不会发生任何事情,因为永远不会满足if条件。)
另请注意,reader != null
的测试在此处是多余的。如果 reader null ,您的代码就会在while (!reader.EndOfStream)
处抛出异常。
将while
循环中的代码更改为:
string currentLine = reader.ReadLine();
if (!string.IsNullOrEmpty(currentLine))
{
//Logic to increment the number is written
//Now saving the change to the file...
string contents = ... get/create contents string from somewhere ...
//contents is the file content with the changed numbers
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
MemoryStream myStream = new MemoryStream(byteArray);
File.AppendAllText("New.txt", contents); //Here is the issue
}
请注意,我使用了string.IsNullOrEmpty()
。根据您的需求和最低要求的框架版本,您可以使用string.IsNullOrWhitespace()
,或只使用if (currentLine != null)
。
(另外,我不知道MemoryStream myStream 的用途是什么。但是,既然你在示例代码中有它,我也将它包含在我的示例代码中,尽管 myStream 在这里没有任何用途。)