{"id":83169,"date":"2023-02-27T07:40:57","date_gmt":"2023-02-27T06:40:57","guid":{"rendered":"https:\/\/code-maze.com\/?p=83169"},"modified":"2024-02-06T10:10:54","modified_gmt":"2024-02-06T09:10:54","slug":"csharp-convert-file-to-byte-array","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/","title":{"rendered":"Convert a File to a Byte Array in C#"},"content":{"rendered":"<p>In this article, we will learn about situations where we may need to convert a file into a byte array. Additionally, we will learn two ways to perform the conversion in C#.<\/p>\n<p>If you want to learn how to <strong>convert a byte array to a file<\/strong>, check out our <a href=\"https:\/\/code-maze.com\/convert-byte-array-to-file-csharp\/\" target=\"_blank\" rel=\"noopener\">convert byte array to a file<\/a> article.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/files-csharp\/FileToByteArray\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>So let&#8217;s start.<\/p>\n<h2>What is a Byte Array?<\/h2>\n<p>In C#, a byte array is an array of 8-bit unsigned integers (bytes). They are often used to represent more complex data structures, such as text, images, or audio data.<\/p>\n<p>There are several use cases in which we want to convert a file to a byte array, some of them are:<\/p>\n<ul>\n<li>Loading file contents into memory for processing<\/li>\n<li>Network transmission of file data<\/li>\n<li>File format conversion<\/li>\n<li>File encryption<\/li>\n<\/ul>\n<p>Generally, a byte array is declared using the <code>byte[]<\/code> syntax:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">byte[] byteArray = new byte[50];<\/code><\/p>\n<p>This creates a byte array with 50 elements.<\/p>\n<h3>Some Initial Setup<\/h3>\n<p>Each of our examples in this article is exercised through the unit test project. The unit tests will create temporary files for the tests and delete them when all the tests have finished executing. For more about unit testing with <strong>xUnit<\/strong> and the <code>IClassFixture&lt;T&gt;<\/code> be sure to check out our article &#8220;<a href=\"https:\/\/code-maze.com\/csharp-testing-framework-differences-between-nunit-xunit-and-mstest\/\" target=\"_blank\" rel=\"noopener\">Differences Between NUnit, xUnit and MSTest<\/a>&#8220;<\/p>\n<p><strong>When converting a file into a byte array it is important to remember that if the file size exceeds <\/strong><code>Array.MaxLength<\/code><strong>, we will not be able to read all of the contents at once. Attempting to do so will result in an exception. <\/strong>In the last section of our article, we will review a technique for solving this problem by working on the file in chunks.<\/p>\n<h2>Use ReadAllBytes to Convert a File<\/h2>\n<p>One of the most straightforward methods for converting a file is the <code>File.ReadAllBytes()<\/code> static method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public void GivenFile_WhenConvertingUsingReadAllBytes_ThenReturnsCorrectContent()\r\n{\r\n    var bytes = File.ReadAllBytes(fixture.SmallTestFile);\r\n\r\n    bytes.Should().BeEquivalentTo(fixture.SmallTestFileExpectedBytes);\r\n}<\/pre>\n<p>This method opens the file, reads all of the contents into an array, and returns it.<\/p>\n<p>If we are working with asynchronous code, we can use the <code>File.ReadAllBytesAsync()<\/code> method to accomplish the same goal:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public async void GivenFile_WhenConvertingUsingReadAllBytesAsync_ThenReturnsCorrectContent()\r\n{\r\n    var bytes = await File.ReadAllBytesAsync(fixture.SmallTestFile);\r\n\r\n    bytes.Should().BeEquivalentTo(fixture.SmallTestFileExpectedBytes);\r\n}<\/pre>\n<h2>Convert Using MemoryStream<\/h2>\n<p>A second technique we can consider for converting a file to a byte array is to stream the file into a <code>MemoryStream<\/code>. While this results in additional memory pressure, if we already have an open <code>FileStream<\/code> object, we can write the stream directly into a <code>MemoryStream<\/code> and then return the result as an array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static byte[] ConvertUsingMemoryStream(string filePath)\r\n{\r\n    using var fs = File.OpenRead(filePath);\r\n    using var ms = new MemoryStream(DefaultBufferSize);\r\n\r\n    fs.CopyTo(ms);\r\n\r\n    return ms.ToArray();\r\n}<\/pre>\n<p>The code here is pretty straightforward. We open a <code>FileStream<\/code> for reading. Next, we initialize a new <code>MemoryStream<\/code> using a <code>DefaultBufferSize<\/code> constant (4096 for our example) as our initial stream capacity to reduce the number of reallocations in the <code>MemoryStream<\/code> while processing the file. Once our initial setup is done we simply copy the <code>FileStream<\/code> to our <code>MemoryStream<\/code> and then convert the <code>MemoryStream<\/code> to an array.<\/p>\n<p>As with the <code>File.ReadAllBytes()<\/code> method, we can also perform a conversion using a <code>MemoryStream<\/code> in an asynchronous fashion:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static async Task&lt;byte[]&gt; ConvertUsingMemoryStreamAsync(string filePath)\r\n{\r\n    await using var fs = File.OpenRead(filePath);\r\n    await using var ms = new MemoryStream(DefaultBufferSize);\r\n\r\n    await fs.CopyToAsync(ms);\r\n\r\n    return ms.ToArray();\r\n}<\/pre>\n<h2>Convert a File Using a Rented Byte Array<\/h2>\n<p>Both of the previous techniques involved creating new arrays (or in the case of the <code>MemoryStream<\/code> potentially multiple new arrays). With the introduction of <code>ArrayPool&lt;T&gt;<\/code> to C#, we have some additional options that will allow us to load the contents of a file into memory without additional memory pressure. This proves especially useful when processing a large number of files and only needing the data in memory temporarily.<\/p>\n<p>For a deeper dive into <code>ArrayPool&lt;T&gt;<\/code>, don&#8217;t miss our article: <a href=\"https:\/\/code-maze.com\/csharp-arraypool-memory-optimization\/\" target=\"_blank\" rel=\"noopener\">&#8220;Memory Optimization With ArrayPool in C#&#8221;<\/a>. Now, let&#8217;s see how we can optimize our memory usage while loading files into a byte array.<\/p>\n<h3>Read File Into Rented Byte Array<\/h3>\n<p>Our first option is to rent an array, load the file data into it, and return the rented array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static (byte[] rentedArray, int length) ConvertToPooledArray(string filePath)\r\n{\r\n    var fileInfo = new FileInfo(filePath);\r\n    ArgumentOutOfRangeException.ThrowIfGreaterThan(fileInfo.Length, Array.MaxLength, \"File length\");\r\n\r\n    var length = (int)fileInfo.Length;\r\n    var array = ArrayPool&lt;byte&gt;.Shared.Rent(length);\r\n    var span = array.AsSpan(0, length);\r\n\r\n    using var fs = fileInfo.OpenRead();\r\n    fs.ReadExactly(span);\r\n\r\n    return (array, length);\r\n}<\/pre>\n<p>Here, we first load the file information and ensure the length is within the bounds of <code>Array.MaxLength<\/code>. Next, we cast the file length value to an int (which we know is safe because of our previous validation). Using this length we rent an array from the shared <code>ArrayPool&lt;byte&gt;<\/code>, and then take a <code>Span&lt;byte&gt;<\/code> of the appropriate length over the rented array. <strong>We take a<\/strong> <code>Span<\/code> <strong>over the array because arrays rented from the <\/strong><code>ArrayPool<\/code><strong> may be longer than the requested size<\/strong>.<\/p>\n<p>Next, we open a <code>FileStream<\/code> for reading and read the file contents into the span. Finally, we return a <code>ValueTuple<\/code> containing the rented array and the length of the file. We return the length because a rented array may be larger than the requested size.<\/p>\n<p><strong>It is important to note here that to prevent memory leaks, the caller of this method must return the rented array to the <\/strong><code>ArrayPool<\/code>:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">ArrayPool&lt;byte&gt;.Shared.Return(rentedArray);<\/code><\/p>\n<p>As with our previous methods, the conversion method can also be written asynchronously:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"8\">public static async Task&lt;(byte[] rentedArray, int length)&gt; ConvertToPooledArrayAsync(string filePath)\r\n{\r\n    var fileInfo = new FileInfo(filePath);\r\n    ArgumentOutOfRangeException.ThrowIfGreaterThan(fileInfo.Length, Array.MaxLength, \"File length\");\r\n\r\n    var length = (int) fileInfo.Length;\r\n    var array = ArrayPool&lt;byte&gt;.Shared.Rent(length);\r\n    var memory = array.AsMemory(0, length);\r\n\r\n    await using var fs = fileInfo.OpenRead();\r\n    await fs.ReadExactlyAsync(memory);\r\n\r\n    return (array, length);\r\n}<\/pre>\n<p>Note here that because we are in an asynchronous method, we must use a <code>Memory&lt;byte&gt;<\/code> rather than a <code>Span&lt;byte&gt;<\/code>. <code>Span<\/code> is a <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/builtin-types\/ref-struct\" target=\"_blank\" rel=\"nofollow noopener\">ref struct<\/a>, and so it cannot be used in an asynchronous context.<\/p>\n<h3>Convert to Byte Array Using ArrayPoolBufferedWriter<\/h3>\n<p>Similar to our technique using <code>MemoryStream<\/code>, we can make use of <code>ArrayPoolBufferedWriter<\/code> which is available in the <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/communitytoolkit\/high-performance\/introduction\" target=\"_blank\" rel=\"nofollow noopener\">CommunityToolkit.HighPerformance package<\/a>.<\/p>\n<p>First, we need to add the package to our project:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">dotnet add package CommunityToolkit.HighPerformance<\/code><\/p>\n<p><code>ArrayPoolBufferedWriter<\/code> behaves much like <code>MemoryStream<\/code>, but instead of allocating new arrays on the heap when the internal buffer is exceeded, it rents them from the <code>ArrayPool<\/code>. This helps to prevent memory pressure and heap fragmentation that can result from\u00a0multiple temporary array allocations:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static byte[] ConvertUsingPooledWriter(string filePath)\r\n{\r\n    using var writer = new ArrayPoolBufferWriter&lt;byte&gt;(DefaultBufferSize);\r\n    using var stream = writer.AsStream();\r\n\r\n    using var fs = File.OpenRead(filePath);\r\n    fs.CopyTo(stream);\r\n\r\n    return writer.WrittenSpan.ToArray();\r\n}<\/pre>\n<p>Here we begin by creating our <code>ArrayPoolBufferWriter<\/code> with our <code>DeafultBufferSize<\/code>. We use an initial buffer size to help avoid reallocations. While in this case, we are not concerned about the memory allocations as a result of exceeding the buffer, we still want to avoid the copying required when the buffer is exceeded.<\/p>\n<p>Next, we create a <code>Stream<\/code> from our buffered writer to enable stream operations on it. Following that we create a <code>FileStream<\/code> to read the contents of our file, and stream them into our buffered writer. Finally, we return the buffered contents as a new array.<\/p>\n<p>As with our previous examples, we can also write this method as <code>async<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static async Task&lt;byte[]&gt; ConvertUsingPooledWriterAsync(string filePath)\r\n{\r\n    using var writer = new ArrayPoolBufferWriter&lt;byte&gt;(DefaultBufferSize);\r\n    await using var stream = writer.AsStream();\r\n\r\n    await using var fs = File.OpenRead(filePath);\r\n    await fs.CopyToAsync(stream);\r\n\r\n    return writer.WrittenSpan.ToArray();\r\n}<\/pre>\n<h2>Converting a Large File to a Byte Array in Chunks<\/h2>\n<p>As we mentioned at the beginning of our article, sometimes it is not possible to load the entire file into memory at one time. When a file&#8217;s length exceeds <code>Array.MaxLength<\/code>, we have to look for an alternative method to deal with the file contents. Here we present one approach making use of <a href=\"https:\/\/code-maze.com\/csharp-async-enumerable-yield\/\" target=\"_blank\" rel=\"noopener\">IAsyncEnumerable<\/a> to return the large file in chunks:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static async IAsyncEnumerable&lt;byte[]&gt; ConvertInChunksMemoryMapped(string filePath, int chunkSize,\r\n    [EnumeratorCancellation] CancellationToken cancellationToken = default)\r\n{\r\n    ArgumentOutOfRangeException.ThrowIfGreaterThan(chunkSize, Array.MaxLength);\r\n\r\n    var rentedBuffer = ArrayPool&lt;byte&gt;.Shared.Rent(chunkSize);\r\n    try\r\n    {\r\n        var memory = rentedBuffer.AsMemory(0, chunkSize);\r\n\r\n        var fileLength = new FileInfo(filePath).Length;\r\n        using var mm = MemoryMappedFile.CreateFromFile(filePath);\r\n        await using var accessor = mm.CreateViewStream(0, fileLength);\r\n\r\n        int bytesRead;\r\n        while ((bytesRead = await accessor.ReadAsync(memory, cancellationToken)) != 0)\r\n            yield return memory[..bytesRead].ToArray();\r\n    }\r\n    finally\r\n    {\r\n        ArrayPool&lt;byte&gt;.Shared.Return(rentedBuffer);\r\n    }\r\n}<\/pre>\n<p>First, we begin by renting a buffer from the <code>ArrayPool<\/code> to use as an internal buffer for reading a chunk of data from the file. Next, we create a <code>Memory&lt;byte&gt;<\/code> over the rented buffer to use in our <code>ReadAsync<\/code> method.<\/p>\n<p>Next, we create a <code>MemoryMappedFile<\/code> from our large file, which allows us to easily process the file in chunks. Once we have our <code>MemoryMappedFile<\/code> we create a <code>MemoryMappedViewStream<\/code> over it, allowing us to process it as a stream. <strong>We need to be careful to specify the length of the view stream, otherwise, the size of the view may be larger than the source file on disk<\/strong>. (For more information, refer to the Microsoft documentation for <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/api\/system.io.memorymappedfiles.memorymappedfile.createviewstream\" target=\"_blank\" rel=\"nofollow noopener\">CreateViewStream<\/a>).<\/p>\n<p>Next, we loop through the stream, reading into our buffer. And lastly, we yield return a new array containing the current file chunk.<\/p>\n<p>Note, for simplicity in the example we are returning a new array for each chunk. <strong>In a production environment, we would want to use a rented array or provide a way for the caller to provide the destination buffer<\/strong>.<\/p>\n<p>We could also write a similar method using <code>FileStream<\/code> (see the GitHub repo for the full code listing) instead of <code>MemoryMappedFile<\/code>, but <code>MemoryMappedFiles<\/code> yield far better performance:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">| Method                   | Mean     | Error    | StdDev   |\r\n|------------------------- |---------:|---------:|---------:|\r\n| ReadFileWithMemoryMapped |  7.046 s | 0.0606 s | 0.0567 s |\r\n| ReadFileWithFileStream   | 13.685 s | 0.2484 s | 0.2324 s |<\/pre>\n<h2>Benchmarking Our Methods<\/h2>\n<p>While each method has its different use cases, it is always a good idea to also consider performance when choosing a method. For our benchmarks, we are asynchronously reading a 17 kb file and computing its MD5 hashcode:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">| Method                   | Mean     | Error   | StdDev   | Median   | Gen0    | Allocated |\r\n|------------------------- |---------:|--------:|---------:|---------:|--------:|----------:|\r\n| ReadFileWithMemoryStream | 254.7 us | 4.17 us |  6.11 us | 252.8 us | 30.7617 |  53.28 KB |\r\n| ReadFileWithReadAllBytes | 257.9 us | 5.06 us |  4.48 us | 256.7 us | 11.7188 |  24.76 KB |\r\n| ReadFileWithPooledWriter | 262.7 us | 5.64 us | 16.55 us | 257.3 us | 12.6953 |  25.25 KB |\r\n| ReadFileWithPooledArray  | 296.5 us | 2.97 us |  2.64 us | 296.6 us |  0.4883 |   1.07 KB |\r\n| ReadFileWithFileStream   | 349.7 us | 4.94 us |  3.85 us | 349.0 us | 14.1602 |  25.34 KB |\r\n| ReadFileWithMemoryMapped | 368.6 us | 7.32 us | 15.29 us | 361.8 us | 12.2070 |  25.09 KB |<\/pre>\n<p>As far as the overall performance goes, there isn&#8217;t much difference between using a <code>MemoryStream<\/code>, calling <code>File.ReadAllBytes<\/code> and using the <code>ArrayPoolBufferWriter<\/code>. Only slightly slower is our method using a rented array, but when considering memory allocations, this method outshines them all. Interestingly, our last place method is the one involving memory mapped files. While this technique shines when processing very large files, for smaller files, it is better to just read the file directly into an array.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we explored several methods for converting a file into an array of bytes. We explored both synchronous and asynchronous techniques. Lastly, we explored a technique for reading a very large file as byte array chunks.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn about situations where we may need to convert a file into a byte array. Additionally, we will learn two ways to perform the conversion in C#. If you want to learn how to convert a byte array to a file, check out our convert byte array to a file [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[10,22],"class_list":["post-83169","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-net","tag-net-core","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Convert a File to a Byte Array in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we discuss use cases for leveraging a byte array and provide two methods to convert a file into a byte array in C#.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Convert a File to a Byte Array in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we discuss use cases for leveraging a byte array and provide two methods to convert a file into a byte array in C#.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-27T06:40:57+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-02-06T09:10:54+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Convert a File to a Byte Array in C#\",\"datePublished\":\"2023-02-27T06:40:57+00:00\",\"dateModified\":\"2024-02-06T09:10:54+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/\"},\"wordCount\":1394,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\".NET\",\".NET CORE\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/\",\"url\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/\",\"name\":\"Convert a File to a Byte Array in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2023-02-27T06:40:57+00:00\",\"dateModified\":\"2024-02-06T09:10:54+00:00\",\"description\":\"In this article, we discuss use cases for leveraging a byte array and provide two methods to convert a file into a byte array in C#.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Convert a File to a Byte Array in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Convert a File to a Byte Array in C# - Code Maze","description":"In this article, we discuss use cases for leveraging a byte array and provide two methods to convert a file into a byte array in C#.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/","og_locale":"en_US","og_type":"article","og_title":"Convert a File to a Byte Array in C# - Code Maze","og_description":"In this article, we discuss use cases for leveraging a byte array and provide two methods to convert a file into a byte array in C#.","og_url":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/","og_site_name":"Code Maze","article_published_time":"2023-02-27T06:40:57+00:00","article_modified_time":"2024-02-06T09:10:54+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Convert a File to a Byte Array in C#","datePublished":"2023-02-27T06:40:57+00:00","dateModified":"2024-02-06T09:10:54+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/"},"wordCount":1394,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":[".NET",".NET CORE"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/","url":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/","name":"Convert a File to a Byte Array in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2023-02-27T06:40:57+00:00","dateModified":"2024-02-06T09:10:54+00:00","description":"In this article, we discuss use cases for leveraging a byte array and provide two methods to convert a file into a byte array in C#.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-convert-file-to-byte-array\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Convert a File to a Byte Array in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/83169","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=83169"}],"version-history":[{"count":4,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/83169\/revisions"}],"predecessor-version":[{"id":108985,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/83169\/revisions\/108985"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=83169"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=83169"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=83169"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}