2017-04-18 38 views
1

所以我想让一个ByteArray文件在二进制文件中显示。使ByteArray显示在二进制文件中

[HttpGet("GetCategoriesInByte")] 
    public byte[] GetCategoriesInByte() 
    { 
     List<object> categoryList = new List<object>(); 
     var categories = Database.Categories 
      .Where(eachCategoryEntity => eachCategoryEntity.DeletedAt == null).AsNoTracking(); 
     foreach (var category in categories) 
     { 
      categoryList.Add(new 
      { 
       CategoryId = category.CategoryId, 
       CategoryName = category.CategoryName, 
       CreatedAt = category.CreatedAt, 
       UpdatedAt = category.UpdatedAt, 
       DeletedAt = category.DeletedAt 
      }); 
     } 

     JsonSerializer jsonSerializer = new JsonSerializer(); 
     MemoryStream memoryStream = new MemoryStream(); 
     BsonWriter bsonWriter = new BsonWriter(memoryStream); 
     jsonSerializer.Serialize(bsonWriter, categoryList); 

     byte[] categoryListArray = Encoding.ASCII.GetBytes(categoryList.ToString()); 
     return categoryListArray; 
    }//End of GetCategoriesInByte 

输出现在是:

“U3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuTGlzdGAxW1N5c3RlbS5PYmplY3Rd”

我希望它是这样的:

00100100 ..等等

我想将它作为byte []发送并显示为二进制。

我该怎么做?提前致谢。

+0

你在哪里看到这个输出?你想在哪里显示它? –

+0

不,“二进制字符串”是错误的。 – Enigmativity

+0

@OfirWinegarten我只想在控制台中看到它,它不会被显示,我只是希望它显示在Binary中。现在我正在使用PostMan和API来显示给我的输出。 –

回答

0

尝试以下操作:

  memoryStream.Position = 0; // reset memory string to beginning after write all data 
      BinaryReader reader = new BinaryReader(memoryStream); 
      byte[] data = reader.ReadBytes((int)memoryStream.Length); 
      string hex = string.Join("", data.Select(x => x.ToString("x2"))); 
+0

感谢您的回复,但我不想返回一个字符串。 –

+0

最后一行转换为字符串是没有必要的。只是包括在内,以获得与您的请求类似的十六进制值。 – jdweng