rspec/rules/S2674/csharp/rule.adoc

61 lines
1.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
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
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
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
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
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
}
}
}
----
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[]