字节只返回一个值的二元解读。 C# [英] Binary Reading of Bytes Returning only One Value. C#
本文介绍了字节只返回一个值的二元解读。 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
控制台显示0,0,0,0时,我期待0,1,2,3。
The console displays 0,0,0,0 when I am expecting 0,1,2,3.
这是修改后的版本:https://msdn.microsoft.com/en-us/library/system.io.binarywriter(v=vs.110).aspx
using System;
using System.IO;
namespace testingfilereadwrite
{
class Program
{
const string FileName = "TestFile.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
Console.ReadKey();
}
public static void WriteDefaultValues()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(FileName, FileMode.Create)))
{
writer.Write(0);
writer.Write(1);
writer.Write(2);
writer.Write(3);
}
}
public static void DisplayValues()
{
byte byte1;
byte byte2;
byte byte3;
byte byte4;
if (File.Exists(FileName))
{
using (BinaryReader reader = new BinaryReader(File.Open(FileName, FileMode.Open)))
{
byte1 = reader.ReadByte();
byte2 = reader.ReadByte();
byte3 = reader.ReadByte();
byte4 = reader.ReadByte();
}
Console.WriteLine(byte1);
Console.WriteLine(byte2);
Console.WriteLine(byte3);
Console.WriteLine(byte4);
}
}
}`
为什么它只有0显示?我怎样才能得到它显示我需要什么?此外,当我使用的不是字节以外的东西,比如字符串或INT为什么它的工作原理。
Why does it display only 0? How can I get it to display what I need? Also, why does it work when I use something other than byte, like string or int.
推荐答案
由于你正在写整数文件和前4个字节0。
Because you are writing integers to the file and the first 4 bytes are 0.
public static void WriteDefaultValues()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(FileName, FileMode.Create)))
{
writer.Write((byte)0);
writer.Write((byte)1);
writer.Write((byte)2);
writer.Write((byte)3);
}
}
试试。
这篇关于字节只返回一个值的二元解读。 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文