如何在 C# 中从字节数组中删除和添加字节

Dav*_*man 2 .net c# arrays

我有一个配置文件 (.cfg),用于创建命令行应用程序以将用户添加到 SFTP 服务器应用程序。

cfg 文件需要为 cfg 文件中的每个条目保留一定数量的保留字节。我目前只是通过创建字节数组并将其转换为字符串,然后将其复制到文件中,将新用户附加到文件末尾,但我遇到了障碍。配置文件需要在文件末尾有 4 个字节。

我需要完成的过程是从文件中删除这些尾随字节,附加新用户,然后将字节附加到末尾。

现在您已经了解了我的问题背后的一些背景。

这是问题:

如何从字节数组中删除和添加字节?

这是我到目前为止得到的代码,它从一个文件读取用户并将其附加到另一个文件。

static void Main(string[] args)
        {
            System.Text.ASCIIEncoding code = new System.Text.ASCIIEncoding();     //Encoding in ascii to pick up mad characters
            StreamReader reader = new StreamReader("one_user.cfg", code, false, 1072);

            string input = "";
            input = reader.ReadToEnd();

            //convert input string to bytes
            byte[] byteArray = Encoding.ASCII.GetBytes(input);
            MemoryStream stream = new MemoryStream(byteArray);

            //Convert Stream to string
            StreamReader byteReader = new StreamReader(stream);
            String output = byteReader.ReadToEnd();
            int len = System.Text.Encoding.ASCII.GetByteCount(output);

            using (StreamWriter writer = new StreamWriter("freeFTPdservice.cfg", true, Encoding.ASCII, 5504))
            {
                writer.Write(output, true);
                writer.Close();
            }

            Console.WriteLine("Appended: " + len);
            Console.ReadLine();
            reader.Close();
            byteReader.Close();
        }
Run Code Online (Sandbox Code Playgroud)

为了尝试说明这一点,这里有一个“图表”。

1)添加第一个用户

文件(附加文本)末尾字节(零)

2) 添加第二个用户

文件(附加文本)(附加文本)末尾字节(零)

等等。

Mat*_*son 5

明确回答您的问题:如何从字节数组中删除和添加字节?

您只能通过创建一个新数组并将字节复制到其中来完成此操作。

幸运的是,这可以通过使用来简化Array.Resize()

byte[] array = new byte[10];
Console.WriteLine(array.Length); // Prints 10
Array.Resize(ref array, 20);     // Copies contents of old array to new.
Console.WriteLine(array.Length); // Prints 20
Run Code Online (Sandbox Code Playgroud)

如果您需要从开头删除字节 -首先Array.Copy字节然后调整大小(如果您不喜欢,则复制到新数组ref):

// remove 42 bytes from beginning of the array, add size checks as needed
Array.Copy(array, 42, array, 0, array.Length-42);
Array.Resize(ref array, array.Length-42);   
Run Code Online (Sandbox Code Playgroud)