Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I wanted to convert a binary file to a byte array and save the output to a text file

My code appears below:
C#
using System;
using System.IO;

namespace WindowsFormsApp9
{
	
	internal static partial class Program
	{
		
		[STAThread]
		private static void Main()
		{
			FileStream stream = File.OpenRead("C:\\\\Users\\\\Sniper\\\\Desktop\\\\array3.bin");
			byte[] fileBytes = new byte[stream.Length];
			stream.Read(fileBytes, 0, fileBytes.Length);
			stream.Close();
			File.WriteAllBytes("C:\\\\Users\\\\Sniper\\\\Desktop\\\\array3.txt", (byte[])Program.byteArr);
		}
	}
}

This is the line that doesn't work:
C#
File.WriteAllBytes(@"C:\\Users\\Sniper\\Desktop\\array3.txt", 
(byte[])byteArr);

Picture describing the problem:
https://g.top4top.io/p_2072tzl4e1.png[^]
What can I do?

What I have tried:

I tried many times but failed every time
Posted
Updated 3-Sep-21 1:28am

1 solution

Read the error message again. Your byte array is called fileBytes, but you are trying to write an uninitalized field called byteArr into the file.

Your code can be simplified to:
C#
using System;
using System.IO;

internal static class Program
{
    static void Main()
    {
        byte[] fileBytes = File.ReadAllBytes(@"C:\Users\Sniper\Desktop\array3.bin");
        File.WriteAllBytes(@"C:\Users\Sniper\Desktop\array3.txt", fileBytes);
    }
}
But this code makes no sense. You are simply copying the file and changing the extension. The bytes from the source file almost certainly won't make sense as text.
 
Share this answer
 
v2
Comments
Nisrja 3-Sep-21 7:55am    
Thank you for the helpful answer
Yes, the code seems meaningless
Please help me
I want to convert a binary file to a byte array and save the byte array in a text file
What is the correct code for that?
please guide me
Richard Deeming 3-Sep-21 9:13am    
That depends on what you mean by saving a byte array in a text file. You need to decide what format you want to use.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900