如何序列化写为字符串的bytearray,以便以后可以读取字节数组? [英] How do I serialize a bytearray written as a string so that the byte array can be read later?

查看:86
本文介绍了如何序列化写为字符串的bytearray,以便以后可以读取字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有要求,例如我将正常字符串转换为bytearray然后将其存储到文件中。我想再次从文件中读取字节数组,将其转换为普通字符串。

我试过以下代码但似乎没有工作







Hi I have requirement such as I am converting a normal string into a bytearray and then storing it into a file. I want to read the byte array again from the file to convert it into normal string.
I have tried the following code but none seems to work



    private void button1_Click(object sender, RoutedEventArgs e)
    {
        int i = 0;
        int j = 0;
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

        // Set filter for file extension and default file extension
        dlg.DefaultExt = ".txt";
        dlg.Filter = "Text documents (.txt)|*.txt";

        // Display OpenFileDialog by calling ShowDialog method
        Nullable<bool> result = dlg.ShowDialog();

        // Get the selected file name and display in a TextBox
        if (result == true)
        {
            button2.IsEnabled = true;
            // Open document
            string filename = dlg.FileName;
            try
            {
                using (StreamReader sr = new StreamReader(filename))
                {
                    String line;

                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.Contains("Vault Serial"))
                        {
                            string[] words = line.Split(':');
                            vault_srno = words[1].Trim();
                            textBox1.Text = vault_srno;
                        }
                        if (line.Contains("Vault Angel Product Key"))
                        {
                            string[] words=line.Split(':');
                            emailnotification_srno = words[1].Trim();
                            textBox2.Text = emailnotification_srno;
                        }
                        if (line.Contains("Number of Licenses"))
                        {
                            string[] words = line.Split(':');
                            number_users = words[1].Trim();
                            textBox3.Text = number_users;
                        }
                        if (line.Contains("License Type"))
                        {
                            string[] words = line.Split(':');
                            lic_type = words[1].Trim();
                            textBox4.Text = lic_type;
                        }
                        if (line.Contains("Vault selected to configure"))
                        {
                            string[] words = line.Split(':');
                            vaults[i,0] = words[1].Trim();
                        }
                        if (line.Contains("Number of Users"))
                        {
                            string[] words = line.Split(':');
                            vaults[i, 1] = words[1].Trim();
                            i++;
                        }
                    }
                }
                while (vaults[j, 0] != null || vaults[j,1]!=null)
                {
                    sb.Append(vaults[j,0]);
                    sb.Append(" ");
                    sb.Append(vaults[j, 1]);
                    sb.Append(" ");
                    /*textBlock1.Text = vaults[j, 0];
                    textBlock1.Text = " ";
                    textBlock1.Text = vaults[j, 1];
                    textBlock1.Text = " ";*/
                    j++;
                }
                textBlock1.Text = sb.ToString();
                /*for (int j = 0; j < vaults.Length/2; j++)
                {
                    MessageBox.Show(vaults[j, 0]);
                    MessageBox.Show(vaults[j, 1]);
                }*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        parsefields();
    }
    public string ConvertStringToHex(String input, System.Text.Encoding encoding)
    {
        Byte[] stringBytes = encoding.GetBytes(input);
        StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
        foreach (byte b in stringBytes)
        {
            sbBytes.AppendFormat("{0:X2}", b);

        }
        return sbBytes.ToString();
    }
    private void parsefields()
    {
        int i = 0;
        StringBuilder sb = new StringBuilder();
        byte[] vaultBytes = Encoding.ASCII.GetBytes(vault_srno);
        byte[] emailBytes = Encoding.ASCII.GetBytes(emailnotification_srno);
        byte[] numb_lic = Encoding.ASCII.GetBytes(number_users);
        byte[] type = Encoding.ASCII.GetBytes(lic_type);
        byte[] notif = Encoding.ASCII.GetBytes("VaultSerialNo");
        byte[] notif2 = Encoding.ASCII.GetBytes("EmailNotificationNo");
        byte[] notif3 = Encoding.ASCII.GetBytes("NumberOfLicenses");
        byte[] notif4 = Encoding.ASCII.GetBytes("LicenseType");
        byte[] notif5 = Encoding.ASCII.GetBytes("Vaults");
        /*foreach (byte b in notif)
            sb.Append(b);*/
        foreach (byte b in vaultBytes)
            sb.Append(b);
        sb.Append("/");
        foreach (byte b in notif2)
            sb.Append(b);
        foreach (byte b in emailBytes)
            sb.Append(b);
        sb.Append("/");
        foreach (byte b in notif3)
            sb.Append(b);
        foreach (byte b in numb_lic)
            sb.Append(b);
        sb.Append("/");
        foreach (byte b in notif4)
            sb.Append(b);
        foreach (byte b in type)
            sb.Append(b);
        sb.Append("/");
        foreach (byte b in notif5)
            sb.Append(b);
        while(vaults[i,0]!=null || vaults[i,1]!=null)
        {
            foreach (byte b in vaults[i, 0])
                sb.Append(b);
            sb.Append("-");
            foreach (byte b in vaults[i, 1])
                sb.Append(b);
            sb.Append(",");
            i++;
        }
        unparse(sb.ToString());
        try
        {
            StreamWriter sw = new StreamWriter("C:\\Vault Angel Licences\\VA_" + vault_srno + ".lic");
            sw.WriteLine(sb.ToString());

            sw.Close();
            MessageBox.Show("Vault Angel licence successfully exported to C:\\Vault Angel Licences\\" + vault_srno + ".lic");

        }
        catch
        {
            MessageBox.Show("Error in Saving");
        }
    }
    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
    private void unparse(string ps)
    {
        string[] words = ps.Split('/');
        textBox6.Text = words[0];
        textBox7.Text = words[1];
        textBox8.Text = words[2];
        textBox9.Text = words[3];
        textBox10.Text = words[4];
        //byte[] byteval=new byte[200];
        byte[] value = GetBytes(words[0]);
        //string something = Encoding.ASCII.GetString(words[0]);
    }
}

推荐答案

看看这个:ByteArrayBuilder - 字节的StringBuilder [ ^ ] - 这就是我用来做的事情:它让我从中构建一个字节数组标准数据类型,然后我将其保存到磁盘。当我读回文件时,我可以非常轻松地将数组撤消回标准数据类型。



并且很容易为字节数组添加加密所以您的许可证数据难以阅读...



BTW:使用硬编码文件夹是一个坏主意,尤其是挂在特定驱动器根目录下的文件夹 - 当这通常是启动驱动器时,这是一个非常糟糕的主意。如果我的启动驱动器是只读的,会发生什么?

相反,请考虑保持数据更合适的位置:我应该在哪里存储我的数据? [ ^ ] - 这样系统会为你跟踪它,你就不会有问题。
Have a look at this: ByteArrayBuilder - a StringBuilder for Bytes[^] - it's what I use to do that: it lets me build up an array of bytes from the standard datatypes and then I save it to disk. When I read the file back, I can "undo" the array back to the standard datatypes very easily.

And it's pretty easy to add encryption to the byte array so your licence data is harder to read...

BTW: It's a bad idea to use a hardcoded folder, and especially one hanging off the root of a specific drive - and when that is normally the boot drive it's a very poor idea. What happens if my boot drive is read only?
Instead, consider keeping your data is a more appropriate place: Where should I store my data?[^] - that way teh system will keep track of it for you and you won't have problems.

这篇关于如何序列化写为字符串的bytearray,以便以后可以读取字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆