문제

나는있다 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