2009-12-08 4 views
2

나는 long 배열을 가지고 있습니다. 이 배열을 이진 파일에 쓰는 방법? 문제는 배열을 byte 배열로 변환하면 일부 값이 변경된다는 것입니다.C# 긴 형식 배열을 이진 파일로 작성하는 방법

long array = new long[160000]; 

일부 코드를 보내기

배열과 같다.

+0

"변경됨"이란 무엇을 말합니까? –

답변

5

BinaryFormatter가 가장 쉽습니다.

또한 valuetypes (나는 이것이 길이를 의미하는 것으로 가정 함)는 매우 효율적으로 직렬화합니다.

+0

바이너리 포맷터와 일치합니다. –

2
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); 
    } 
} 
+0

그건 아주 느릴 것입니다,하지만 작동합니다 :) – leppie

+0

@ 레피, 나는 당신과 동의합니다. 일부 측정을 수행하고 제안 된대로 BinaryFormatter를 사용하면 성능이 향상됩니다. –

1

값은 어떻게 변경됩니까? 그리고 긴 배열은 바이트 배열에 매우 빨리 복사 할 수 있으므로 직렬화가 필요 없습니다.

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(); 
     } 
관련 문제