为什么我需要循环读取的字节数

为什么我需要循环读取的字节数

本文介绍了FileStream.Read - 为什么我需要循环读取的字节数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从MSDN获得以下代码。



所以,我不明白为什么我必须循环FileStream.Read,当它返回与文件相同的值时每次都是长度。

numBytesToRead将结束为零,FileStream.Read只执行一次。

评论说read可以返回从0到numBytesToRead的任何内容,这意味着从偏移到数量吧?

那么有人可以解释为什么以及偏移和计数的功能是什么?

先谢谢。



  public   static   void  Main()
{
// 指定一个文件到读取和创建。
string pathSource = @ C:\tests\source.txt;
string pathNew = @ c:\\ \\tests\\\
ewfile.txt;

尝试
{

使用(FileStream fsSource = new FileStream(pathSource,
FileMode.Open,FileAccess.Read))
{

// 将源文件读入字节数组。
byte [] bytes = new 字节 [fsSource.Length];
int numBytesToRead =( int )fsSource.Length;
int numBytesRead = 0 ;
while (numBytesToRead > 0
{
// 读取可能会返回任何内容0到numBytesToRead。
int n = fsSource.Read(bytes,numBytesRead,numBytesToRead);

// 到达文件末尾时中断。
if (n == 0
断裂;

numBytesRead + = n;
numBytesToRead - = n;
}
numBytesToRead = bytes.Length;

// 将字节数组写入另一个FileStream。
使用(FileStream fsNew = new FileStream(pathNew,
FileMode.Create,FileAccess.Write))
{
fsNew.Write(bytes, 0 ,numBytesToRead);
}
}
}
catch (FileNotFoundException ioEx)
{
Console.WriteLine (ioEx.Message);
}
}
解决方案



Got the code below from MSDN.

So, I don't understand why I had to loop FileStream.Read when it return the same value as the file length everytime.
The numBytesToRead will end up zero and FileStream.Read only executed once.
The comment said that "read may return anything from 0 to numBytesToRead", that means from offset to count right?
So can someone explain why and what's the function of offset and count?
Thanks before.

public static void Main()
{
    // Specify a file to read from and to create. 
    string pathSource = @"c:\tests\source.txt";
    string pathNew = @"c:\tests\newfile.txt";

    try
    {

        using (FileStream fsSource = new FileStream(pathSource,
            FileMode.Open, FileAccess.Read))
        {

            // Read the source file into a byte array. 
            byte[] bytes = new byte[fsSource.Length];
            int numBytesToRead = (int)fsSource.Length;
            int numBytesRead = 0;
            while (numBytesToRead > 0)
            {
                // Read may return anything from 0 to numBytesToRead. 
                int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

                // Break when the end of the file is reached. 
                if (n == 0)
                    break;

                numBytesRead += n;
                numBytesToRead -= n;
            }
             numBytesToRead = bytes.Length;

            // Write the byte array to the other FileStream. 
            using (FileStream fsNew = new FileStream(pathNew,
                FileMode.Create, FileAccess.Write))
            {
                fsNew.Write(bytes, 0, numBytesToRead);
            }
        }
    }
    catch (FileNotFoundException ioEx)
    {
        Console.WriteLine(ioEx.Message);
    }
}
解决方案



这篇关于FileStream.Read - 为什么我需要循环读取的字节数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 12:32