C # كيفية كتابة مجموعة طويلة من نوع إلى الملف الثنائي

StackOverflow https://stackoverflow.com/questions/1865824

  •  18-09-2019
  •  | 
  •  

سؤال

انا املك long مجموعة مصفوفة. كيفية كتابة هذه الصفيف إلى ملف ثنائي؟ المشكلة هي أنه إذا قمت بتحويلها إلى byte صفيف يتم تغيير بعض القيم.

مجموعة مثل:

long array = new long[160000];

إعطاء بعض القصاصات رمز.

هل كانت مفيدة؟

المحلول

ستكون BinaryFormatter أسهل.

أيضا Valuetypes (أفترض أن هذا هو ما تقصده لفترة طويلة)، يسقط بكفاءة للغاية.

نصائح أخرى

var array = new[] { 1L, 2L, 3L };
using (var stream = new FileStream("test.bin", FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new BinaryWriter(stream))
{
    foreach (long item in array)
    {
        writer.Write(item);
    }
}

كيف تغيرت القيم؟ ومجموعة طويلة يمكن نسخها إلى مجموعة من البايت بسرعة كبيرة، لا حاجة إلى التسلسل.

 static void Main(string[] args) {

            System.Random random = new Random();

            long[] arrayOriginal = new long[160000];
            long[] arrayRead = null;

            for (int i =0 ; i < arrayOriginal.Length; i++) {
                arrayOriginal[i] = random.Next(int.MaxValue) * random.Next(int.MaxValue);
            }

            byte[] bytesOriginal = new byte[arrayOriginal.Length * sizeof(long)];
            System.Buffer.BlockCopy(arrayOriginal, 0, bytesOriginal, 0, bytesOriginal.Length);

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) {

                // write 
                stream.Write(bytesOriginal, 0, bytesOriginal.Length);

                // reset
                stream.Flush();
                stream.Position = 0;

                int expectedLength = 0;
                checked {
                    expectedLength = (int)stream.Length;
                }
                // read
                byte[] bytesRead = new byte[expectedLength];

                if (expectedLength == stream.Read(bytesRead, 0, expectedLength)) {
                    arrayRead = new long[expectedLength / sizeof(long)];
                    Buffer.BlockCopy(bytesRead, 0, arrayRead, 0, expectedLength);
                }
                else {
                    // exception
                }

                // check 
                for (int i = 0; i < arrayOriginal.Length; i++) {
                    if (arrayOriginal[i] != arrayRead[i]) {
                        throw new System.Exception();
                    }
                }
            }

            System.Console.WriteLine("Done");
            System.Console.ReadKey();
        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top