Home > Net >  How to save a char[25] when it contains only 6 chars C#
How to save a char[25] when it contains only 6 chars C#

Time:02-18

I have a class that contains as follow

public class foo
{
    public long id= 0;
    public char[] TestId = new char[25];// new char[25];
    public char[] GUID = new char[64]; //new char[64];
    public char[] sign = new char[61];//new char[61];
    public int DemandDate = 0;
    public int CompleteDate = 0;
    public int DownloadDate = 0;

}
    static public void WriteFile(string fileName, List<ClientInfo> list)
    {
        using (FileStream fs = new FileStream(fileName, FileMode.Create))
        {
            using (var writer = new BinaryWriter(fs, Encoding.UTF8, false))
            {
                foreach(ClientInfo ci in list)
                {
                    WriteClientInfo(writer, offset, ociv);
                    offset  = header.recordSize;
                }
            }
        }
    }

    private static void WriteClientInfo(BinaryWriter writer, int offset, ClientInfo ci)
    {
        try
        {
            writer.Write(ci.ID);
            writer.Write(ci.TestId, 0, 25);
            writer.Write(ci.GUID, 0, 64 );
            writer.Write(ci.Sign, 0, 61);
            writer.Write(ci.DemandDate);
            writer.Write(ci.CompleteDate);
            writer.Write(ci.DownloadDate);
        }
        catch (Exception ex)
        {

        }
    }

when I serialize this ci.TestId will crash, stating that the index is out of range. I know that the value in ci.TestId = FD3394, but I need to be able to save the length of 25 char, not the actual length of the ci.TestId. Because I read this structure from a program that is written in C , and it has to be the exact size, of the length of the char in the definition, not what is used. I modify it in C# but needs to be read back in C as well.

CodePudding user response:

I would check that serialized ClientInfo data isn't truncating/trimming the ci.TestId. Are you sure that the ci.TestId looks something like: 'FD3394 '. (i.e. with some sort of front for rear padding. Otherwise, my guess is that you will not be able to write 25 chars count if it doen't actually have 25 char. Maybe formatting ci.TestId with padding when writing.

CodePudding user response:

You can use the PadLeft() or PadRight() method like this

TestId = TestId.PadLeft(25);

The left side will be filled with spaces.

You have to convert it to a string and then re-convert it to char[]

TestId = _testId.PadLeft(25).ToCharArray();

CodePudding user response:

Modify your writer code:

if(ci.TestId.Length >= 25){
  writer.Write(ci.TestId, 0, 25);
} else (
  writer.Write(ci.TestId);
  writer.Write(new char[25-ci.TestId.Length]);
}

If you want the nils on the left, write them first:

else (
  writer.Write(new char[25-ci.TestId.Length]);
  writer.Write(ci.TestId);
}
  • Related