rspec/rules/S2674/csharp/rule.adoc
2024-08-12 13:34:34 +02:00

79 lines
2.7 KiB
Plaintext

== Why is this an issue?
Invoking a stream reading method without verifying the number of bytes read can lead to erroneous assumptions. A Stream can represent any I/O operation, such as reading a file, network communication, or inter-process communication. As such, it is not guaranteed that the `byte[]` passed into the method will be filled with the requested number of bytes. Therefore, inspecting the value returned by the reading method is important to ensure the number of bytes read.
Neglecting the returned length read can result in a bug that is difficult to reproduce.
This rule raises an issue when the returned value is ignored for the following methods:
* https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.read[Stream.Read]
* https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.readasync[Stream.ReadAsync]
* https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.readatleast[Stream.ReadAtLeast]
* https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.readatleastasync[Stream.ReadAtLeastAsync]
== How to fix it
Check the return value of stream reading methods to verify the actual number of bytes read, and use this value when processing the data to avoid potential bugs.
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public byte[] ReadFile(string fileName)
{
using var stream = File.Open(fileName, FileMode.Open);
var result = new byte[stream.Length];
stream.Read(result, 0, (int)stream.Length); // Noncompliant
return result;
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
public byte[] ReadFile(string fileName)
{
using var stream = File.Open(fileName, FileMode.Open);
using var ms = new MemoryStream();
var buffer = new byte[1024];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
----
== Resources
=== Documentation
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.read[Stream.Read Method]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.readasync[Stream.ReadAsync Method]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.readatleast[Stream.ReadAtLeast Method]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.readatleastasync[Stream.ReadAtLeastAsync Method]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]