C#用filestream和CryptoStream加密解密的问题

在写用filestream进行加密的时候发现:每次写入的句子开头是乱码,除了第一次

img


(第一次写入的结果)

img


(第二次写入的结果)

这是我写的将字符串加密写入文件的代码

            using (AesCryptoServiceProvider crypt = new AesCryptoServiceProvider())
            {
                crypt.Key = Encoding.ASCII.GetBytes("7819450510000000");
                crypt.IV = Encoding.ASCII.GetBytes("7819450510000000");

                using (FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write))
                    {
                        using (CryptoStream cs = new CryptoStream(fs, crypt.CreateEncryptor(), CryptoStreamMode.Write))
                        {

                            byte[] str = Encoding.UTF8.GetBytes(DateTime.Now.ToString("MM-dd hh:mm:ss") + "——" + status + "——" + message + "——" + type + "——" + "耗时" + timespan + "ms"+"\r\n");
                            cs.Write(str, 0, str.Length);

                        }
                    }

            }

这是我写的解密读取文件的代码

                using (AesCryptoServiceProvider crypt = new AesCryptoServiceProvider())
                {
                    crypt.Key = Encoding.ASCII.GetBytes("7819450510000000");
                    crypt.IV = Encoding.ASCII.GetBytes("7819450510000000");
                        using (FileStream fs = new FileStream(Application.StartupPath + @"\操作日志\" + listView1.SelectedItems[0].SubItems[1].Text, FileMode.Open, FileAccess.Read))
                        {
                            using (CryptoStream cs = new CryptoStream(fs, crypt.CreateDecryptor(), CryptoStreamMode.Read))
                            {
                                string s="";
                                while (true)
                                {
                                    byte[] buffer = new byte[1024 * 1024 * 10];
                                    int r = cs.Read(buffer, 0, buffer.Length);
                                    s += Encoding.UTF8.GetString(buffer, 0, r);
                                    if (r == 0) break;
                                }
                                textBox3.Text = s;

                            }
                        }

                }

希望大家指点指点QAQ

既然你加密了,那你应该存成二进制文件,不要存文本
加密过后是byte数组,不是每个字节都可以转化成可见的字符的
你读取也要按照二进制方式读取,然后解密,才能够还原回字符串