How do you remove and add bytes from a byte array

2019-01-20 17:23发布

I have a configuration file (.cfg) that I am using to create a command line application to add users to a SFTP server application.

The cfg file needs to have a certain number of reserved bytes for each entry in the cfg file. I am currently just appending a new user to the end of the file by creating a byte array and converting it to a string, then copying it to the file, but i've hit a snag. The config file requires 4 bytes at the end of the file.

The process I need to accomplish is to remove these trailing bytes from the file, append the new user, then append the bytes to the end.

So, now that you have some context behind my problem.

Here is the question:

How do you remove and add bytes from a byte array?

Here is the code I've got so far, it reads the user from one file and appends it to another.

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();
        }

To try and illustrate this point, here is a "diagram".

1) Add first user

File(appended text)Bytes at end (zeros)

2) Add second user

File(appended text)(appended text)bytes at end (zeros)

and so on.

2条回答
走好不送
2楼-- · 2019-01-20 17:44

You don't. You can copy to a new array of the desired size. Or you can work with a List<byte> and then create an array from that.

But, in your case, I would suggest looking into the file streams themselves... they let you read and write individual bytes or byte arrays and also:

which lets you move around to arbitrary locations in the file... So, for the use case you described, you would

  • open the file (for read/write access)
  • move to the end of the file
  • move back four bytes (do you know which ones they are? if not, this would be a good time to stash them)
  • write the new user
  • write the four bytes
  • close the file

Something like this:

using (var fs = new FileStream(PATH, FileMode.Open, FileAccess.ReadWrite))
{
    fs.Seek(-4, SeekOrigin.End);
    fs.Write(userBytes);
    fs.Write(fourBytesAtEnd);      
}

This also has the advantage of not having to slurp in the whole file and write it back out.

查看更多
萌系小妹纸
3楼-- · 2019-01-20 17:48

To explicitly answer your question: How do you remove and add bytes from a byte array?

You can only do this by creating a new array and copying the bytes into it.

Fortunately, this is simplified by using 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

If you need to remove bytes from the beginning - Array.Copy bytes first and than resize (or copy to new array if you don't like 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);   
查看更多
登录 后发表回答