FileStream添加“额外"字符到TXT文件 [英] FileStream adding "extra" characters to TXT file
问题描述
我读取TXT文件还是XML文件都没关系,我总是看到额外"信息添加到我的文件中并保存到磁盘.我们首先执行以下操作:
It does not matter if I read a TXT file or a XML file I always see "extra" info added into my file which is saved to disk. We first do the following:
FileStream fs = new FileStream(fileMoverFile.SourcePath, FileMode.Open, FileAccess.Read);
然后将fs
分配给Stream
类型的变量,该变量将传递给以下函数:
Then we assign fs
to a variable of type Stream
which we pass to the function below:
private void SaveToDisk(Stream fileStream, string saveToPath)
{
if (!Directory.Exists(Path.GetDirectoryName(saveToPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(saveToPath));
}
FileStream outputStream = new FileInfo(saveToPath).OpenWrite();
const int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead = fileStream.Read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.Write(buffer, 0, bufferSize);
bytesRead = fileStream.Read(buffer, 0, bufferSize);
}
outputStream.Close();
}
当我打开保存到磁盘的文件时,我看到了额外的信息,这些信息基本上是同一文件的某些内容,并重复了一些不属于该文件的信息. 很奇怪.
When I open the file which was saved to disk, I see extra information which is basically some content of the same file being repeated with some other info which do not belong to the file. Very strange.
这可能是什么原因造成的?
What could be causing this?
推荐答案
您需要写入bytesRead
个字节,而不是bufferSize
个字节:
You need to write bytesRead
bytes, not bufferSize
bytes:
int bytesRead = fileStream.Read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.Write(buffer, 0, bytesRead); // Change this here
现在,当您到达输入流的末尾时,您正在写入的数据可能要多于读入的数据,这将在文件末尾引起额外的垃圾".
Right now, when you reach the end of the input stream, you're potentially writing more data than you read in, which will cause "extra garbage" at the end of the file.
That being said, if your goal is just to copy the stream, you could just use Stream.CopyTo (provided you're in .NET 4+). This avoids the read/write loop entirely, and simplifies your code dramatically:
private void SaveToDisk(Stream fileStream, string saveToPath)
{
if (!Directory.Exists(Path.GetDirectoryName(saveToPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(saveToPath));
}
using(FileStream outputStream = new FileInfo(saveToPath).OpenWrite())
{
fileStream.CopyTo(outputStream);
}
}
这篇关于FileStream添加“额外"字符到TXT文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!