Home > front end >  store byte[] into file C#
store byte[] into file C#

Time:10-24

I have this function reading website names one at a time and creating an object array for each url where the website name and bytes received from the webpage is saved into the array. This array is then saved into a txt file called "saveData.txt"

                string[] readText = File.ReadAllLines("new.txt");
                foreach (string s in readText)
                {
                    
                    object[] url = new object[2];
                    url[0] = s;
                    url[1] = displayByteCode(s);
                     
                    
                    using (StreamWriter writer = new StreamWriter("saveData.txt",true))
                    {
                        writer.WriteLine(url[0] " "  url[1]);
                    }
                   

                }

The displayByteCode is a function that is as follows:

public byte[] displayByteCode(string getURLCode)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(getURLCode);
            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponse();
            MemoryStream ms = new MemoryStream();
            myResponse.GetResponseStream().CopyTo(ms);
            byte[] data = ms.ToArray();
            
            return data;

        }

it is to return the bytes received from the website. While the url is saved properly. the byte is saved as "System.Byte[]" how do i save the actually byte instead of this? Thank you for your help!

CodePudding user response:

when you call operator on a string and an object, it calls toStirng method on that object (this is why it writes System.Byte[] on file)

you can't write both string and bytes in c#, for storing bytes, you can use :

File.WriteAllBytes("saveData.txt", (byte[])url[1]);

or you can convert it to string and store it :

writer.WriteLine(url[0] " "  Convert.ToBase64String((byte[])url[1]));
  • Related