-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamHelper.cs
More file actions
81 lines (72 loc) · 2.7 KB
/
StreamHelper.cs
File metadata and controls
81 lines (72 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// <copyright file="StreamHelper.cs" company="SoluiNet">
// Copyright (c) SoluiNet. All rights reserved.
// </copyright>
namespace SoluiNet.Core.Tools.Stream
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Provides a collection of methods to work with streams.
/// </summary>
public static class StreamHelper
{
/// <summary>
/// Convert a stream to a string.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="encoding">The encoding. If not provided UTF-8 will be used.</param>
/// <returns>Returns a <see cref="string"/> for the contents of the <see cref="Stream"/>.</returns>
public static string StreamToString(System.IO.Stream stream, Encoding encoding = null)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (encoding == null)
{
encoding = Encoding.UTF8;
}
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// Convert a stream to a string.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="encoding">The encoding. If not provided UTF-8 will be used.</param>
/// <returns>Returns a <see cref="string"/> for the contents of the <see cref="Stream"/>.</returns>
public static string ReadStringFromStream(this System.IO.Stream stream, Encoding encoding = null)
{
return StreamToString(stream, encoding);
}
/// <summary>
/// Convert stream to byte array (taken from: https://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream).
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>Returns the converted stream as byte array.</returns>
public static byte[] ToByteArray(this System.IO.Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
var buffer = new byte[16 * 1024];
using (var memoryStream = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, read);
}
return memoryStream.ToArray();
}
}
}
}