Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ public static void CopyToFile(MemoryStream stream, string path)
stream.CopyTo(fileStream);
}

public static async Task CopyToFileAsync(MemoryStream stream, string path)
{
await using var fileStream = File.Create(path);
stream.Position = 0;
await stream.CopyToAsync(fileStream);
}

public static void WriteToFileStream(MemoryStream stream, string path)
{
using var fileStream = File.Create(path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.12" />
<PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,55 @@
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;

namespace HowToConvertAStreamToAFileInCSharp;

[InProcess]
[MemoryDiagnoser]
[Orderer(BenchmarkDotNet.Order.SummaryOrderPolicy.FastestToSlowest)]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class ConvertAStreamToAFileInCSharpBenchmark
{
public static MemoryStream Stream { get; set; } = new MemoryStream();
private readonly MemoryStream _stream = new();
private string _destinationPath = string.Empty;

public static string DestinationPath { get; set; } = string.Empty;
[GlobalSetup]
public void Setup()
{
_destinationPath = Path.Combine(AppContext.BaseDirectory, "Files");

using var fileStream = File.OpenRead(Path.Combine(_destinationPath, "source.png"));
fileStream.CopyTo(_stream);
}

[GlobalCleanup]
public void Cleanup() => _stream.Dispose();

[Benchmark]
public void CopyToBenchmark()
{
ConvertAStreamToAFileInCSharp.CopyToFile(Stream, Path.Combine([DestinationPath, "CopyTo.png"]));
ConvertAStreamToAFileInCSharp.CopyToFile(_stream, Path.Combine(_destinationPath, "CopyTo.png"));
}

[Benchmark]
public async Task CopyToAsyncBenchmark()
{
await ConvertAStreamToAFileInCSharp.CopyToFileAsync(_stream, Path.Combine(_destinationPath, "CopyToAsync.png"));
}

[Benchmark]
public void WriteBenchmark()
{
ConvertAStreamToAFileInCSharp.WriteToFileStream(Stream, Path.Combine([DestinationPath, "Write.png"]));
ConvertAStreamToAFileInCSharp.WriteToFileStream(_stream, Path.Combine(_destinationPath, "Write.png"));
}

[Benchmark]
public void WriteByteBenchmark()
{
ConvertAStreamToAFileInCSharp.WriteByteToFileStream(Stream, Path.Combine([DestinationPath, "WriteByte.png"]));
ConvertAStreamToAFileInCSharp.WriteByteToFileStream(_stream, Path.Combine(_destinationPath, "WriteByte.png"));
}

[Benchmark]
public void WriteAllBytesBenchmark()
{
ConvertAStreamToAFileInCSharp.WriteAllBytesFile(Stream, Path.Combine([DestinationPath, "WriteAllBytes.png"]));
ConvertAStreamToAFileInCSharp.WriteAllBytesFile(_stream, Path.Combine(_destinationPath, "WriteAllBytes.png"));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
using System.Reflection;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Running;
using HowToConvertAStreamToAFileInCSharp;

var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(directory))
{
return;
}

var sourceFile = Path.Combine([directory, "Files", "source.png"]);
var destinationPath = Path.Combine([directory, "Files"]);
var directory = AppContext.BaseDirectory;
var sourceFile = Path.Combine(directory, "Files", "source.png");
var destinationPath = Path.Combine(directory, "Files");

using var fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
using var memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream);

ConvertAStreamToAFileInCSharp.CopyToFile(memoryStream, Path.Combine([destinationPath, "CopyTo.png"]));
ConvertAStreamToAFileInCSharp.WriteToFileStream(memoryStream, Path.Combine([destinationPath, "WriteTo.png"]));
ConvertAStreamToAFileInCSharp.WriteByteToFileStream(memoryStream, Path.Combine([destinationPath, "WriteByte.png"]));
ConvertAStreamToAFileInCSharp.WriteAllBytesFile(memoryStream, Path.Combine([destinationPath, "WriteAllBytes.png"]));
Console.WriteLine($"Position after loading: {memoryStream.Position} of {memoryStream.Length}");

using (var noRewindFile = File.Create(Path.Combine(destinationPath, "NoRewind.png")))
{
memoryStream.CopyTo(noRewindFile);
Console.WriteLine($"Bytes written without rewinding: {noRewindFile.Length}");
}

memoryStream.Position = 0;
using (var rewindFile = File.Create(Path.Combine(destinationPath, "Rewind.png")))
{
memoryStream.CopyTo(rewindFile);
Console.WriteLine($"Bytes written after rewinding: {rewindFile.Length}");
Console.WriteLine($"Position after CopyTo: source {memoryStream.Position}, destination {rewindFile.Position}");
}

ConvertAStreamToAFileInCSharpBenchmark.Stream = memoryStream;
ConvertAStreamToAFileInCSharpBenchmark.DestinationPath = destinationPath;
ConvertAStreamToAFileInCSharp.CopyToFile(memoryStream, Path.Combine(destinationPath, "CopyTo.png"));
await ConvertAStreamToAFileInCSharp.CopyToFileAsync(memoryStream, Path.Combine(destinationPath, "CopyToAsync.png"));
ConvertAStreamToAFileInCSharp.WriteToFileStream(memoryStream, Path.Combine(destinationPath, "WriteTo.png"));
ConvertAStreamToAFileInCSharp.WriteByteToFileStream(memoryStream, Path.Combine(destinationPath, "WriteByte.png"));
ConvertAStreamToAFileInCSharp.WriteAllBytesFile(memoryStream, Path.Combine(destinationPath, "WriteAllBytes.png"));

BenchmarkRunner.Run<ConvertAStreamToAFileInCSharpBenchmark>();
BenchmarkRunner.Run<ConvertAStreamToAFileInCSharpBenchmark>(args: args);
Original file line number Diff line number Diff line change
@@ -1,78 +1,102 @@
using System.Reflection;
using HowToConvertAStreamToAFileInCSharp;

namespace Tests;

[TestClass]
public class ConvertAStreamToAFileInCSharpTests
{
private static readonly string FilesPath = Path.Combine(AppContext.BaseDirectory, "Files");
private static readonly string SourceFile = Path.Combine(FilesPath, "source.png");

[TestMethod]
public void WhenCopyToFile_FileExists()
public void WhenCopyToFile_ThenFileHasTheSourceBytes()
{
var destinationPath = GetPath();
var memoryStream = GetMemoryStream();
ConvertAStreamToAFileInCSharp.CopyToFile(memoryStream, Path.Combine([destinationPath, "CopyTo.png"]));
var path = Path.Combine(FilesPath, "CopyTo.png");
using var memoryStream = GetMemoryStream();

ConvertAStreamToAFileInCSharp.CopyToFile(memoryStream, path);

Assert.IsTrue(File.Exists(Path.Combine([destinationPath, "CopyTo.png"])));
CollectionAssert.AreEqual(File.ReadAllBytes(SourceFile), File.ReadAllBytes(path));
}

[TestMethod]
public void WhenWriteToFile_FileExists()
public async Task WhenCopyToFileAsync_ThenFileHasTheSourceBytes()
{
var destinationPath = GetPath();
var memoryStream = GetMemoryStream();
ConvertAStreamToAFileInCSharp.WriteToFileStream(memoryStream, Path.Combine([destinationPath, "WriteTo.png"]));
var path = Path.Combine(FilesPath, "CopyToAsync.png");
using var memoryStream = GetMemoryStream();

await ConvertAStreamToAFileInCSharp.CopyToFileAsync(memoryStream, path);

Assert.IsTrue(File.Exists(Path.Combine([destinationPath, "WriteTo.png"])));
CollectionAssert.AreEqual(File.ReadAllBytes(SourceFile), File.ReadAllBytes(path));
}

[TestMethod]
public void WhenWriteByteToFile_FileExists()
public void WhenWriteToFile_ThenFileHasTheSourceBytes()
{
var destinationPath = GetPath();
var memoryStream = GetMemoryStream();
ConvertAStreamToAFileInCSharp.WriteByteToFileStream(memoryStream, Path.Combine([destinationPath, "WriteByte.png"]));
var path = Path.Combine(FilesPath, "WriteTo.png");
using var memoryStream = GetMemoryStream();

Assert.IsTrue(File.Exists(Path.Combine([destinationPath, "WriteByte.png"])));
ConvertAStreamToAFileInCSharp.WriteToFileStream(memoryStream, path);

CollectionAssert.AreEqual(File.ReadAllBytes(SourceFile), File.ReadAllBytes(path));
}

[TestMethod]
public void WhenWriteAllBytesToFile_FileExists()
public void WhenWriteByteToFile_ThenFileHasTheSourceBytes()
{
var destinationPath = GetPath();
var memoryStream = GetMemoryStream();
ConvertAStreamToAFileInCSharp.WriteAllBytesFile(memoryStream, Path.Combine([destinationPath, "WriteAllBytes.png"]));
var path = Path.Combine(FilesPath, "WriteByte.png");
using var memoryStream = GetMemoryStream();

ConvertAStreamToAFileInCSharp.WriteByteToFileStream(memoryStream, path);

Assert.IsTrue(File.Exists(Path.Combine([destinationPath, "WriteAllBytes.png"])));
CollectionAssert.AreEqual(File.ReadAllBytes(SourceFile), File.ReadAllBytes(path));
}

private string GetPath()
[TestMethod]
public void WhenWriteAllBytesToFile_ThenFileHasTheSourceBytes()
{
var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(directory))
{
return string.Empty;
}
var path = Path.Combine(FilesPath, "WriteAllBytes.png");
using var memoryStream = GetMemoryStream();

var destinationPath = Path.Combine([directory, "Files"]);
ConvertAStreamToAFileInCSharp.WriteAllBytesFile(memoryStream, path);

return destinationPath;
CollectionAssert.AreEqual(File.ReadAllBytes(SourceFile), File.ReadAllBytes(path));
}

private MemoryStream GetMemoryStream()
[TestMethod]
public void GivenAStreamAtItsEnd_WhenCopyToWithoutRewinding_ThenFileIsEmpty()
{
var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(directory))
var path = Path.Combine(FilesPath, "NoRewind.png");
using var memoryStream = GetMemoryStream();
Assert.AreEqual(memoryStream.Length, memoryStream.Position);

using (var fileStream = File.Create(path))
{
return null!;
memoryStream.CopyTo(fileStream);
}

var sourceFile = Path.Combine([directory, "Files", "source.png"]);
Assert.AreEqual(0, new FileInfo(path).Length);
}

[TestMethod]
public void WhenCopyTo_ThenBothPositionsEndAfterTheCopiedBytes()
{
using var memoryStream = GetMemoryStream();
memoryStream.Position = 0;
using var destination = new MemoryStream();

using var fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
memoryStream.CopyTo(destination);

Assert.AreEqual(memoryStream.Length, memoryStream.Position);
Assert.AreEqual(memoryStream.Length, destination.Position);
}

private static MemoryStream GetMemoryStream()
{
using var fileStream = new FileStream(SourceFile, FileMode.Open, FileAccess.Read);
var memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream);

return memoryStream;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Expand All @@ -10,10 +10,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
<PackageReference Include="coverlet.collector" Version="10.1.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="MSTest.TestAdapter" Version="4.5.3" />
<PackageReference Include="MSTest.TestFramework" Version="4.5.3" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading