CopyFileEx “The parameter is invalid” error

后端 未结 2 357
萌比男神i
萌比男神i 2020-12-21 15:21

I\'m writing a (fairly) simple C# application using .NET 4 to check for updates before running an executable. If a newer version of an exe exists on a network share, simply

2条回答
  •  天命终不由人
    2020-12-21 15:50

    Instead of calling ReadBytes(), which allocates a new byte[] buffer array on every call, allocate a single buffer (of, say 64KB in size) and call Read(buf, 0, buf.Length), which will read up to buf.Length bytes into the array and then return the actual number of bytes read. Then re-use that same buffer array for every read (after writing out its contents to the target stream). This saves having to re-allocate a new buffer for each read/write operation.

    Example

    For example, the inner loop of a stream copying method would look something like this:

    byte[]  buf;
    
    // Allocate an I/O data buffer
    buf = new byte[64*1024];
    
    // Copy the contents of the input stream to the output stream
    for (;;)
    {
        int     len;
    
        // Read a block of data from the input stream
        len = inp.ReadBytes(buf, 0, buf.Length);
        if (len <= 0)
            break;
    
        // Write the data to the output stream
        outp.Write(buf, 0, len);
    }
    

    The loop reads up to 64KB of bytes from the input stream into the buffer, then writes out the actual number of bytes read to the output stream. The same buffer is used for each read/write operation, so we're not doing unnecessary allocations and deallocations of buffers. When the read operation fails, we've reached the end of the input stream, so we exit the loop.

提交回复
热议问题