gpt4 book ai didi

c# - FileStream 返回长度 = 0

转载 作者:行者123 更新时间:2023-12-04 18:03:57 25 4
gpt4 key购买 nike

我正在尝试读取本地文件并将其上传到 ftp 服务器。当我读取图像文件时,一切正常,但是当我读取 doc 或 docx 文件时,FileStream 返回长度 = 0。这是我的代码:我检查了一些其他文件,它似乎只适用于图像,并且对任何其他文件返回 0

if (!ftpClient.FileExists(fileName))
{
try
{
ftpClient.ValidateCertificate += (control, e) => { e.Accept = true; };

const int BUFFER_SIZE = 64 * 1024; // 64KB buffer
byte[] buffer = new byte[BUFFER_SIZE];
using (Stream readStream = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read))
using (Stream writeStream = ftpClient.OpenWrite(fileName))
{
while (readStream.Position < readStream.Length)
{
buffer.Initialize();
int bytesRead = readStream.Read(buffer, 0, BUFFER_SIZE);
writeStream.Write(buffer, 0, bytesRead);
}
readStream.Flush();
readStream.Close();
writeStream.Flush();
writeStream.Close();
DeleteTempFile(tempFilePath);
return true;
}
}
catch (Exception ex)
{
return false;
}
}

我找不到它有什么问题。你能帮帮我吗?

最佳答案

虽然这不能回答您的具体问题,但您实际上不需要知道流的长度。继续阅读,直到达到零长度阅读。 A zero byte read is guaranteed to indicate the the end of any stream .

Return Value

Type: System.Int32

The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

while (true)
{
int bytesRead = readStream.Read(buffer, 0, BUFFER_SIZE);
if(bytesRead==0)
{
break;
}
writeStream.Write(buffer, 0, bytesRead);
}

或者:

readStream.CopyTo(writeStream);

可能是陈述您的目标的最简洁的方法...

关于c# - FileStream 返回长度 = 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30185265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com