简体   繁体   中英

store byte[] into file C#

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!

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]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM