c# - FileStream 返回长度 = 0

标签 c# asp.net filestream

我正在尝试读取本地文件并将其上传到 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/

相关文章:

c# - 使用 lambda 从 List 获取数组数组?

c# - 哪些 Java/Scala 或 .NET Web 框架支持修改源代码并立即运行工作流 e.i.没有很长的重建/重新部署程序?

javascript - 为什么我的 ASP.net 函数只执行一次?

sql-server - 使用 SQL Server 2012 FileTable 创建目录后资源管理器未更新

c# - 找不到“文件流”

c# - 如果时区规则更改,以前保存的日期时间的 UTC 到本地时间转换

c# - 反射和属性使用的资源

javascript - 使用 Javascript 启用验证器

c# - jquery触发c#函数

apache-flex - 如何使用 flash.filesystem.FileStream