从二进制文件中读取寄存器

时间:2012-02-06 12:14:45

标签: c# c#-2.0

在二进制文件寄存器中写入后包含以下内容的程序:

StringBuilder name0 = new StringBuilder(15);
int stock0, safe0;
double cost0;

必须通过根据注册表的位置提供id来读取一个注册表的数据。

因为注册表是20个字节,每个注册表的pos将是:

pos = (id-1) * 20;

正确?

问题是StringBuilder不能保存15个字符,而是每次写入的名称长度,而不是读取您需要的数据,而是读取垃圾。是不是有办法声明一个总是具有确切大小的字符串,以便正确读取数据?

代码:

public static void Main(string[] args)
{
    Console.WriteLine("Give file name: ");
    string f = Console.ReadLine();

    StringBuilder name0 = new StringBuilder(15);
    bool criterion = true;
    int stock0, safe0;
    double cost0;
    long id, pos;

    try
    {
        FileStream fs = File.Open(f, FileMode.Create, FileAccess.ReadWrite);
        BinaryWriter writer = new BinaryWriter(fs);
        BinaryReader reader = new BinaryReader(fs);

        while (criterion != false)
        {
            Console.WriteLine("Give name (10 char) or STOP for end");
            name0.Insert(0, Console.ReadLine());

            if ((name0.ToString()).Equals("STOP"))
                criterion = false;
            else
            {
                Console.WriteLine("Stock : ");
                stock0 = Int32.Parse(Console.ReadLine());

                Console.WriteLine("Safe: ");
                safe0 = Int32.Parse(Console.ReadLine());

                Console.WriteLine("Cost: ");
                cost0 = double.Parse(Console.ReadLine());

                writer.Write(name0.ToString());
                writer.Write(stock0);
                writer.Write(safe0);
                writer.Write(cost0);
            } // else

            name0.Remove(0, name0.Length);

        } //while

        Console.WriteLine(" Give ID: ");
        id = long.Parse(Console.ReadLine());
        pos = (id - 1) * 20; //20 = megethos eggrafis(2 int+ 1db + 16chars)

        if ((pos < fs.Length) && (id != 0))
        {
            fs.Seek(pos, SeekOrigin.Begin);
            name0.Insert(0, reader.ReadChars(name0.Length));
            Console.WriteLine("Name: {0}", name0);
            stock0 = reader.ReadInt32();
            Console.WriteLine("\nStock: {0}", stock0);
            safe0 = reader.ReadInt32();
            Console.WriteLine("\nSafe: {0}", safe0);
            cost0 = reader.ReadDouble();
            Console.WriteLine("\nCost: {0}", cost0);
            name0.Length = 0;
        }

        fs.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

1 个答案:

答案 0 :(得分:0)

除非将其声明为char[15],否则不能在C#中声明固定长度的字符串。但是你可以在阅读时手动填充空格来写入和修剪空格:

// writing
writer.Write(name0.ToString().PadRight(15));

//reading
name0.Insert(0, reader.ReadChars(15));
name0 = new StringBuilder(name0.ToString().Trim());