简体   繁体   English

将字节 [] 存储到文件 C#

[英]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.我有这个功能,一次读取一个网站名称,并为每个 url 创建一个对象数组,其中从网页接收的网站名称和字节保存到数组中。 This array is then saved into a txt file called "saveData.txt"然后将该数组保存到名为“saveData.txt”的 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: displayByteCode 是一个函数,如下所示:

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?字节保存为“System.Byte[]”如何保存实际字节而不是这个? 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)当您在字符串和对象上调用 + 运算符时,它会对该对象调用 toStirng 方法(这就是它在文件上写入 System.Byte[] 的原因)

you can't write both string and bytes in c#, for storing bytes, you can use :你不能在 C# 中同时写字符串和字节,为了存储字节,你可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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