2012-10-01 41 views

回答

0

您可以使用前8個字節來存儲陣列的尺寸:

public static byte[] ToByteArray(string[,] input) 
{ 
    using (var stream = new MemoryStream()) 
    using (var writer = new BinaryWriter(stream, Encoding.UTF8)) 
    { 
     var rows = input.GetLength(0); 
     var cols = input.GetLength(1); 
     writer.Write(rows); 
     writer.Write(cols); 
     for (int i = 0; i < rows; i++) 
     { 
      for (int j = 0; j < cols; j++) 
      { 
       writer.Write(input[i, j]); 
      } 
     } 
     return stream.ToArray(); 
    } 
} 

和字節數組轉換回2D字符串數組:

public static string[,] FromByteArray(byte[] input) 
{ 
    using (var stream = new MemoryStream(input)) 
    using (var reader = new BinaryReader(stream, Encoding.UTF8)) 
    { 
     var rows = reader.ReadInt32(); 
     var cols = reader.ReadInt32(); 
     var result = new string[rows, cols]; 
     for (int i = 0; i < rows; i++) 
     { 
      for (int j = 0; j < cols; j++) 
      { 
       result[i, j] = reader.ReadString(); 
      } 
     } 
     return result; 
    } 
}