rspec/rules/S2674/csharp/rule.adoc

42 lines
1.2 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
You cannot assume that any given stream reading call will fill the ``++byte[]++`` passed in to the method with the number of bytes requested. Instead, you must check the value returned by the read method to see how many bytes were read. Fail to do so, and you introduce a bug that is both harmful and difficult to reproduce.
2020-06-30 12:48:07 +02:00
2021-02-02 15:02:10 +01:00
This rule raises an issue when a ``++Stream.Read++`` or a ``++Stream.ReadAsync++`` method is called, but the return value is not checked.
2020-06-30 12:48:07 +02:00
== Noncompliant Code Example
----
public void DoSomething(string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open))
{
var result = new byte[stream.Length];
stream.Read(result, 0, (int)stream.Length); // Noncompliant
// ... do something with result
}
}
----
== Compliant Solution
----
public void DoSomething(string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open))
{
var buffer = new byte[1024];
using (var ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
// ... do something with ms
}
}
}
----
include::../see.adoc[]