本文整理汇总了C#中BinaryReader.ReadChar方法的典型用法代码示例。如果您正苦于以下问题:C# BinaryReader.ReadChar方法的具体用法?C# BinaryReader.ReadChar怎么用?C# BinaryReader.ReadChar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BinaryReader
的用法示例。
在下文中一共展示了BinaryReader.ReadChar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: loadCharArray
public static char[] loadCharArray(string filename)
{
if(!EasySave.fileExists(filename))
{
Debug.LogError("Could not load file: File does not exist.");
return null;
}
BinaryReader br = new BinaryReader(new MemoryStream(getBytesFromFile(filename)));
try
{
int noOfItems = br.ReadInt32();
char[] result = new char[noOfItems];
for(int i=0;i<noOfItems;i++)
{
result[i] = br.ReadChar();
}
br.Close();
return result;
}
catch(Exception e)
{
Debug.LogError("Could not load file: File specified is not in the correct format.\nDetails: "+e.Message);
}
return null;
}
示例2: StreamTest
public static async Task StreamTest(Stream stream, Boolean fSuppress)
{
string strValue;
int iValue;
//[] We will first use the stream's 2 writing methods
int iLength = 1 << 10;
stream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < iLength; i++)
stream.WriteByte((byte)i);
byte[] btArr = new byte[iLength];
for (int i = 0; i < iLength; i++)
btArr[i] = (byte)i;
stream.Write(btArr, 0, iLength);
//we will write many things here using a binary writer
BinaryWriter bw1 = new BinaryWriter(stream);
bw1.Write(false);
bw1.Write(true);
for (int i = 0; i < 10; i++)
{
bw1.Write((byte)i);
bw1.Write((sbyte)i);
bw1.Write((short)i);
bw1.Write((char)i);
bw1.Write((UInt16)i);
bw1.Write(i);
bw1.Write((uint)i);
bw1.Write((Int64)i);
bw1.Write((ulong)i);
bw1.Write((float)i);
bw1.Write((double)i);
}
//Some strings, chars and Bytes
char[] chArr = new char[iLength];
for (int i = 0; i < iLength; i++)
chArr[i] = (char)i;
bw1.Write(chArr);
bw1.Write(chArr, 512, 512);
bw1.Write(new string(chArr));
bw1.Write(new string(chArr));
//[] we will now read
stream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < iLength; i++)
{
Assert.Equal(i % 256, stream.ReadByte());
}
btArr = new byte[iLength];
stream.Read(btArr, 0, iLength);
for (int i = 0; i < iLength; i++)
{
Assert.Equal((byte)i, btArr[i]);
}
//Now, for the binary reader
BinaryReader br1 = new BinaryReader(stream);
Assert.False(br1.ReadBoolean());
Assert.True(br1.ReadBoolean());
for (int i = 0; i < 10; i++)
{
Assert.Equal( (byte)i, br1.ReadByte());
Assert.Equal((sbyte)i, br1.ReadSByte());
Assert.Equal((short)i, br1.ReadInt16());
Assert.Equal((char)i, br1.ReadChar());
Assert.Equal((UInt16)i, br1.ReadUInt16());
Assert.Equal(i, br1.ReadInt32());
Assert.Equal((uint)i, br1.ReadUInt32());
Assert.Equal((Int64)i, br1.ReadInt64());
Assert.Equal((ulong)i, br1.ReadUInt64());
Assert.Equal((float)i, br1.ReadSingle());
Assert.Equal((double)i, br1.ReadDouble());
}
chArr = br1.ReadChars(iLength);
for (int i = 0; i < iLength; i++)
{
Assert.Equal((char)i, chArr[i]);
}
chArr = new char[512];
chArr = br1.ReadChars(iLength / 2);
for (int i = 0; i < iLength / 2; i++)
{
Assert.Equal((char)(iLength / 2 + i), chArr[i]);
}
chArr = new char[iLength];
for (int i = 0; i < iLength; i++)
//.........这里部分代码省略.........
示例3: netEvent
void netEvent(NetworkPlayer player,int tick,string name, byte[] data)
{
MemoryStream stream = new MemoryStream(data);
BinaryReader reader = new BinaryReader(stream);
System.Type type = System.Type.GetType(name);
if (type == null)
return;
if (!typeof(NetworkEvent).IsAssignableFrom(type))
return;
NetworkEvent eventType = Activator.CreateInstance(type,tick) as NetworkEvent;
if (eventType.type == NetworkSendType.Everyone)
if (player == Network.player)
{
return;
}
eventType.player = player;
FieldInfo[] info = type.GetFields();
int mask = reader.ReadInt32();
for (int i = 0; i < info.Length; i++)
{
if ((mask & (1 << i+1)) == 0)
continue;
if (info[i].FieldType.Name == "Single")
{
float val = reader.ReadSingle();
info[i].SetValue(eventType, val);
}
else if (info[i].FieldType.Name == "Char")
{
char val = reader.ReadChar();
info[i].SetValue(eventType, val);
}
else if (info[i].FieldType.Name == "Type")
{
string nm = reader.ReadString();
Type t = Type.GetType(nm);
info[i].SetValue(eventType, t);
}
else if (info[i].FieldType.Name == "Boolean")
{
bool val = reader.ReadBoolean();
info[i].SetValue(eventType, val);
}
else if (info[i].FieldType.Name == "Byte")
{
byte val = reader.ReadByte();
info[i].SetValue(eventType, val);
}
else if (info[i].FieldType.Name == "String")
{
string val = reader.ReadString();
info[i].SetValue(eventType, val);
}
else if (info[i].FieldType.Name == "Int32")
{
int val = reader.ReadInt32();
info[i].SetValue(eventType, val);
}
else if (info[i].FieldType.Name == "Vector2")
{
Vector2 val = new Vector2(reader.ReadSingle(), reader.ReadSingle());
info[i].SetValue(eventType, val);
}
else if (info[i].FieldType.Name == "Int32[]")
{
int len = reader.ReadInt32();
int[] val = new int[len];
for (int j = 0; j < val.Length; j++)
val[j] = reader.ReadInt32();
info[i].SetValue(eventType, val);
}
else if (info[i].FieldType.Name == "tUpdate[]")
{
int len = reader.ReadInt32();
tUpdate[] val = new tUpdate[len];
for (int j = 0; j < val.Length; j++)
{
byte t = reader.ReadByte();
if (t == 1)
val[j] = new terrainDmg();
else if (t == 2)
val[j] = new terrainAddBlock();
FieldInfo[] field = val[j].GetType().GetFields();
for (int k = 0; k < field.Length; k++)
{
if (field[k].FieldType.Name == "Int32")
{
//.........这里部分代码省略.........
示例4: Load3DS
public int Load3DS(string p_filename)
{
int i; //Index variable
objects = new Hashtable();
ambient = new Hashtable();
diffuse = new Hashtable();
specular = new Hashtable();
shininess = new Hashtable();
shininessST = new Hashtable();
obj_type p_object = null;
BinaryReader l_file; //File pointer
ushort l_chunk_id; //Chunk identifier
uint l_chunk_lenght; //Chunk lenght
char l_char; //Char variable
ushort l_qty; //Number of elements in each chunk
ushort l_face_flags; //Flag that stores some face information
bool l_end = false;
string l_mat_name = "";
color_typeF cl;
float per;
using (l_file = new BinaryReader(File.Open(p_filename, FileMode.Open, FileAccess.Read)))
{
while (!l_end) //Loop to scan the whole file
{
try
{
l_chunk_id = l_file.ReadUInt16();
l_chunk_lenght = l_file.ReadUInt32();
switch (l_chunk_id)
{
//----------------- MAIN3DS -----------------
// Description: Main chunk, contains all the other chunks
// Chunk ID: 4d4d
// Chunk Lenght: 0 + sub chunks
//-------------------------------------------
case 0x4d4d:
break;
//----------------- EDIT3DS -----------------
// Description: 3D Editor chunk, objects layout info
// Chunk ID: 3d3d (hex)
// Chunk Lenght: 0 + sub chunks
//-------------------------------------------
case 0x3d3d:
break;
//--------------- EDIT_OBJECT ---------------
// Description: Object block, info for each object
// Chunk ID: 4000 (hex)
// Chunk Lenght: len(object name) + sub chunks
//-------------------------------------------
case 0x4000:
p_object = new obj_type();
p_object.name = "";
p_object.loader = this;
do
{
l_char = l_file.ReadChar();
if (l_char > 0)
p_object.name = p_object.name + l_char;
} while (l_char != 0);
objects.Add(p_object.name, p_object);
break;
//--------------- OBJ_TRIMESH ---------------
// Description: Triangular mesh, contains chunks for 3d mesh info
// Chunk ID: 4100 (hex)
// Chunk Lenght: 0 + sub chunks
//-------------------------------------------
case 0x4100:
break;
//--------------- TRI_VERTEXL ---------------
// Description: Vertices list
// Chunk ID: 4110 (hex)
// Chunk Lenght: 1 x unsigned short (number of vertices)
// + 3 x float (vertex coordinates) x (number of vertices)
// + sub chunks
//-------------------------------------------
case 0x4110:
l_qty = l_file.ReadUInt16();
p_object.vertices_qty = l_qty;
p_object.vertex = new vertex_type[l_qty];
for (i = 0; i < l_qty; i++)
{
p_object.vertex[i].point.x = l_file.ReadSingle();
p_object.vertex[i].point.y = l_file.ReadSingle();
p_object.vertex[i].point.z = l_file.ReadSingle();
}
break;
//--------------- TRI_FACEL1 ----------------
// Description: Polygons (faces) list
//.........这里部分代码省略.........
示例5: StreamTest
private Boolean StreamTest(Stream stream, Boolean fSuppress){
if(!fSuppress)
Console.WriteLine("Testing " + stream.GetType() + " for read/write tests");
String strValue;
Int32 iValue;
Int32 iLength = 1 << 10;
stream.Seek(0, SeekOrigin.Begin);
for(int i=0; i<iLength; i++)
stream.WriteByte((Byte)i);
Byte[] btArr = new Byte[iLength];
for(int i=0; i<iLength; i++)
btArr[i] = (Byte)i;
stream.Write(btArr, 0, iLength);
BinaryWriter bw1 = new BinaryWriter(stream);
bw1.Write(false);
bw1.Write(true);
for(int i=0; i<10; i++){
bw1.Write((Byte)i);
bw1.Write((SByte)i);
bw1.Write((Int16)i);
bw1.Write((Char)i);
bw1.Write((UInt16)i);
bw1.Write(i);
bw1.Write((UInt32)i);
bw1.Write((Int64)i);
bw1.Write((UInt64)i);
bw1.Write((Single)i);
bw1.Write((Double)i);
}
Char[] chArr = new Char[iLength];
for(int i=0; i<iLength;i++)
chArr[i] = (Char)i;
bw1.Write(chArr);
bw1.Write(chArr, 512, 512);
bw1.Write(new String(chArr));
bw1.Write(new String(chArr));
stream.Seek(0, SeekOrigin.Begin);
for(int i=0; i<iLength; i++){
if(stream.ReadByte() != i%256){
return false;
}
}
btArr = new Byte[iLength];
stream.Read(btArr, 0, iLength);
for(int i=0; i<iLength; i++){
if(btArr[i] != (Byte)i){
Console.WriteLine(i + " " + btArr[i] + " " + (Byte)i);
return false;
}
}
BinaryReader br1 = new BinaryReader(stream);
if(br1.ReadBoolean())
return false;
if(!br1.ReadBoolean())
return false;
for(int i=0; i<10; i++){
if(br1.ReadByte() != (Byte)i)
return false;
if(br1.ReadSByte() != (SByte)i)
return false;
if(br1.ReadInt16() != (Int16)i)
return false;
if(br1.ReadChar() != (Char)i)
return false;
if(br1.ReadUInt16() != (UInt16)i)
return false;
if(br1.ReadInt32() != i)
return false;
if(br1.ReadUInt32() != (UInt32)i)
return false;
if(br1.ReadInt64() != (Int64)i)
return false;
if(br1.ReadUInt64() != (UInt64)i)
return false;
if(br1.ReadSingle() != (Single)i)
return false;
if(br1.ReadDouble() != (Double)i)
return false;
}
chArr = br1.ReadChars(iLength);
for(int i=0; i<iLength;i++){
if(chArr[i] != (Char)i)
return false;
}
chArr = new Char[512];
chArr = br1.ReadChars(iLength/2);
for(int i=0; i<iLength/2;i++){
if(chArr[i] != (Char)(iLength/2+i))
return false;
}
chArr = new Char[iLength];
for(int i=0; i<iLength;i++)
chArr[i] = (Char)i;
strValue = br1.ReadString();
if(!strValue.Equals(new String(chArr)))
return false;
strValue = br1.ReadString();
if(!strValue.Equals(new String(chArr))){
return false;
}
//.........这里部分代码省略.........
示例6: ReadString
public static string ReadString(BinaryReader br)
{
int len = br.ReadInt32();
string str = new string(br.ReadChars(len - 1));
br.ReadChar();
return str;
}
示例7: runTest
//.........这里部分代码省略.........
sr2.ReadBoolean();
iCountErrors++;
printerr( "Error_10408! Expected exception not thrown");
} catch (ObjectDisposedException iexc) {
printinfo( "Info_1098t! Caught expected exception, exc=="+iexc.Message);
} catch (Exception exc) {
iCountErrors++;
printerr( "Error_178t5! Incorrect exception thrown, exc=="+exc.ToString());
}
iCountTestcases++;
try {
sr2.ReadByte();
iCountErrors++;
printerr( "Error_17985! Expected exception not thrown");
} catch (ObjectDisposedException iexc) {
printinfo( "Info_0984s! Caught expected exception, exc=="+iexc.Message);
} catch (Exception exc) {
iCountErrors++;
printerr( "Error_019g8! Incorrect exception thrown, excc=="+exc.ToString());
}
iCountTestcases++;
try {
sr2.ReadBytes(2);
iCountErrors++;
printerr( "Error_10989! Expected exception not thrown");
} catch (ObjectDisposedException iexc) {
printinfo( "Info_01099! Caught expectede exception, exc=="+iexc.Message);
} catch (Exception exc) {
iCountErrors++;
printerr( "Error_16794! Incorrect exception thrown, exc=="+exc.ToString());
}
iCountTestcases++;
try {
sr2.ReadChar();
iCountErrors++;
printerr( "ERror_1980f! Expected Exception not thrown");
} catch (ObjectDisposedException iexc) {
printinfo( "Info_1099g! Caught expected exception, exc=="+iexc.Message);
} catch (Exception exc) {
iCountErrors++;
printerr( "Error_1098g! Incorrect exception thrown, exc=="+exc.ToString());
}
iCountTestcases++;
try {
sr2.ReadChars(2);
iCountErrors++;
printerr( "Error_19876! Expected exception not thrown");
} catch (ObjectDisposedException iexc) {
printinfo( "Info_0198c! Caught expected exception, exc=="+iexc.Message);
} catch (Exception exc) {
iCountErrors++;
printerr( "Error_1869g! Incorrect exception thrown, exc=="+exc.ToString());
}
iCountTestcases++;
try {
sr2.ReadDouble();
iCountErrors++;
printerr( "Error_1089g! Expected exception not thrown");
} catch (ObjectDisposedException iexc) {
printinfo( "Info_t5999! Caught expected exception, exc=="+iexc.Message);
} catch (Exception exc) {
iCountErrors++;
printerr( "Error_1900v! Incorrect exception thrown, exc=="+exc.ToString());
}
iCountTestcases++;
try {
示例8: Load
// Binary load
public bool Load(string filename)
{
FileStream binFile = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(binFile);
int size = reader.ReadByte(); countReadBytes++;
string ver = ReadBinString(ref reader, size);
if (ver != BinaryHeaderVersionString)
return false; // bail ;
size = reader.ReadByte(); countReadBytes++;
mFormat = ReadBinString(ref reader, size);
if (mFormat != "MetricsMemoryLog")
return false;
// // Read in string table.
// stringTable.Clear();
// int numberStrings = reader.ReadInt32();
// for (int i = 0; i < numberStrings; i++)
// {
// stringTable.AddUnique( reader.ReadString() );
// }
// Read in categories
categories.Clear();
categories.Add("N/A");
backupCategories.Clear();
// int numberCategories = 3; // reader.ReadByte(); // assuming # of categories < 511
cachedCategoryIndex = 0;
// for (int i = 0, e = numberCategories; i < e; i++)
{
// AddCategory( ReadBinString(ref reader) );
AddCategory("Default");
// AddCategory("Physics");
// AddCategory("Animation");
}
// Read if there are callstacks
byte callstackCode = reader.ReadByte(); countReadBytes++;
bool haveCallstack = callstackCode == 8;
// Read total budget
uint totalBudget = reader.ReadUInt32(); countReadBytes += 4;
// Read in log entries
log.Clear();
UInt32 addrLow = uint.MaxValue;
UInt32 addrHigh = uint.MinValue;
UInt32 logEntries = reader.ReadUInt32(); countReadBytes += 4;
if (logEntries == 0)
logEntries = uint.MaxValue - 1;
UInt32 lastFrameIdx = uint.MaxValue - 1;
for (UInt32 i = 0; i < logEntries; i++)
{
char testread = '0';
try{
testread = reader.ReadChar(); countReadBytes++;
}
catch(System.IO.EndOfStreamException)
{
System.Diagnostics.Debug.Print("End of File reached\n");
break;
}
LogEntry logentry = new LogEntry();
logentry.type = testread;
// logentry.category = (Byte)(1);
if (logentry.type == 'A' || logentry.type == 'F')
{
logentry.address = reader.ReadUInt32(); countReadBytes +=4;
logentry.allocSize = reader.ReadUInt32(); countReadBytes += 4;
addrLow = Math.Min(addrLow, logentry.address);
addrHigh = Math.Max(addrHigh, logentry.address + logentry.allocSize);
}
if (logentry.type == 'A' || logentry.type == 'L')
{
int tagsize = reader.ReadChar(); countReadBytes++;
if(tagsize > 0)
{
string tag = ReadBinString(ref reader, tagsize);
// System.Diagnostics.Debug.Assert(false);
logentry.nameString = AddString(tag.Trim());
// if (logentry.type == 'L')
// System.Diagnostics.Debug.Print("{0}", tag);
}
else
logentry.nameString = AddString("NoTag");
}
else if(logentry.type == 'S')
{
if (i != lastFrameIdx + 1)
{
logentry.nameString = AddString("FRAME");
lastFrameIdx = i;
}
else
{
lastFrameIdx = i;
continue;
//.........这里部分代码省略.........
示例9: Load
// Binary load
public bool Load(string filename)
{
FileStream binFile = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(binFile);
int size = reader.ReadByte();
string ver = ReadBinString(ref reader, size);
if (ver != BinaryHeaderVersionString)
return false; // bail ;
size = reader.ReadByte();
mFormat = ReadBinString(ref reader, size);
if (mFormat != "MetricsMemoryLog")
return false;
// // Read in string table.
// stringTable.Clear();
// int numberStrings = reader.ReadInt32();
// for (int i = 0; i < numberStrings; i++)
// {
// stringTable.AddUnique( reader.ReadString() );
// }
// Read in categories
categories.Clear();
categories.Add("N/A");
backupCategories.Clear();
backupCategories.Add("N/A");
cachedCategoryIndex = 0;
// Read if there are callstacks
byte callstackCode = reader.ReadByte();
bool haveCallstack = callstackCode == 8;
// Read total budget
uint totalBudget = reader.ReadUInt32();
// Read in log entries
log.Clear();
UInt32 addrLow = uint.MaxValue;
UInt32 addrHigh = uint.MinValue;
UInt32 logEntries = reader.ReadUInt32();
// if (logEntries == 0)
logEntries = uint.MaxValue;
UInt32 lastFrameIdx = uint.MaxValue;
uint currCount = 0;
for (UInt32 i = 0;; i++)
{
LogEntry logentry = new LogEntry();
try
{
logentry.type = reader.ReadChar();
// logentry.category = (Byte)(1);
// reading allocation address and size
if (logentry.type == 'A' || logentry.type == 'F')
{
logentry.address = reader.ReadUInt32();
logentry.allocSize = reader.ReadUInt32();
addrLow = Math.Min(addrLow, logentry.address);
addrHigh = Math.Max(addrHigh, logentry.address + logentry.allocSize);
}
// reading tag
if (logentry.type == 'A' || logentry.type == 'L')
{
int tagsize = reader.ReadChar();
if (tagsize > 0)
{
string tag = ReadBinString(ref reader, tagsize);
// System.Diagnostics.Debug.Assert(false);
logentry.nameString = AddString(tag.Trim());
}
else
logentry.nameString = AddString("NoTag");
}
// reading category
if (logentry.type == 'A')
{
// sbyte catIndex = (sbyte)reader.ReadByte();
// if(catIndex >= 0)
// { // so category is already in table
// logentry.category = (byte)catIndex;
// }
// else
// { // this is a new category. Add it to the table
int catSize = reader.ReadChar();
string cat = ReadBinString(ref reader, catSize);
logentry.category = AddCategory(cat.Trim());
// }
}
// reading frame swap. This serves as time counter
if (logentry.type == 'S')
{
if (i != lastFrameIdx + 1)
//.........这里部分代码省略.........
示例10: getTag
static string getTag(BinaryReader br)
{
//read a tag from br <tag> and return the tag name
string tag = "";
char c = 'x';
while (c != '<')
c = br.ReadChar();
while (c != '>')
{
c = br.ReadChar();
if (c != '>')
tag += c.ToString();
}
return tag;
}
示例11: ReceiveClientState
// MARK: Network IO
void ReceiveClientState()
{
var readable = new ArrayList();
const int POLL_TIME = 50000; // 0.05 seconds
readable.Add(clientSock);
Socket.Select(readable, null, null, POLL_TIME);
if (readable.Count == 0) return;
var handler = clientSock.Accept();
var stop = Stopwatch.StartNew();
using (var stream = new NetworkStream(handler)) {
// Read device ID header
var reader = new BinaryReader(stream);
int header = (int)reader.ReadChar(); // header as 1 byte number
SetHeadsetNumber(header, true);
ReadLines(stream);
}
handler.Close();
clientSock.Close();
stop.Stop();
UnityEngine.Debug.Log(string.Format("Receiving lines took {0} milliseconds", stop.ElapsedMilliseconds));
receivedData = true;
}
示例12: getData
static string getData(BinaryReader br)
{
//read data upto closing tag
string data = "";
char c = 'x';
while (c != '<')
{
c = br.ReadChar();
if (c != '<')
data += c.ToString();
}
while (c != '>')
c = br.ReadChar();
//swap %l and %g to < and >
data = data.Replace("%l", "<").Replace("%g", ">");
return data;
}
示例13: runTest
public bool runTest()
{
Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
String strValue = String.Empty;
Random rand = new Random( (int) DateTime.Now.Ticks );
int[] iArrInvalidValues = new Int32[]{ -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue, Int16.MinValue};
int[] iArrLargeValues = new Int32[]{ Int32.MaxValue, Int32.MaxValue-1, Int32.MaxValue/2 , Int32.MaxValue/10 , Int32.MaxValue/100 };
int[] iArrValidValues = new Int32[]{ 10000, 100000 , Int32.MaxValue/2000 , Int32.MaxValue/10000, Int16.MaxValue };
try
{
BinaryReader sr2;
StreamWriter sw2;
MemoryStream ms2;
FileStream fs2;
Char[] chArrReturn;
String filName = s_strTFAbbrev+"Test.tmp";
if(File.Exists(filName))
File.Delete(filName);
strLoc = "Loc_948yv";
ms2 = new MemoryStream();
sr2 = new BinaryReader(ms2);
iCountTestcases++;
for(int iLoop = 0 ; iLoop < iArrInvalidValues.Length ; iLoop++ )
{
try
{
sr2.ReadChars(iArrInvalidValues[iLoop]);
iCountErrors++;
printerr( "Error_1098g! Expected exception not thrown");
}
catch (ArgumentOutOfRangeException aexc)
{
printinfo( "Info_7587b! Caught expected exception, exc=="+aexc.Message);
}
catch (Exception exc)
{
iCountErrors++;
printerr( "Error_789gy! Incorrect exception thrown, exc=="+exc.ToString());
}
}
sr2.Close();
strLoc = "Loc_948yv";
ms2 = new MemoryStream();
sw2 = new StreamWriter(ms2);
for(int i = 0 ; i < chArr.Length ; i++)
sw2.Write(chArr[i]);
sw2.Flush();
ms2.Position = 0;
sr2 = new BinaryReader(ms2);
iCountTestcases++;
char[] cNewArray = null ;
for(int iLoop = 0 ; iLoop < iArrLargeValues.Length ; iLoop++ )
{
try
{
cNewArray = sr2.ReadChars(iArrLargeValues[iLoop]);
if(!( cNewArray.Length == 0 || cNewArray.Length == 22))
{
iCountErrors++;
printerr( "Error_5543! Unexpected bytes are read from the stream... Length:" + cNewArray.Length);
}
}
catch (OutOfMemoryException aexc)
{
printinfo( "Info_7342! Caught expected exception, exc=="+aexc.Message);
}
catch (Exception exc)
{
iCountErrors++;
printerr( "Error_0843! Incorrect exception thrown, exc=="+exc.ToString());
}
}
sr2.Close();
strLoc = "Loc_7t09b";
ms2 = new MemoryStream();
ms2.Write(new Byte[]{1}, 0, 1);
ms2.Position = 0;
sr2 = new BinaryReader(ms2);
iCountTestcases++;
chArrReturn = sr2.ReadChars(3);
if(chArrReturn.Length != 1)
{
iCountErrors++;
printerr( "Error_2098uv! Read from empty stream, read=="+chArrReturn.Length);
}
sr2.Close();
strLoc = "Loc_2698b";
try
{
ms2 = new MemoryStream();
sw2 = new StreamWriter(ms2);
for(int i = 0 ; i < chArr.Length ; i++)
sw2.Write(chArr[i]);
sw2.Flush();
ms2.Position = 0;
sr2 = new BinaryReader(ms2);
chArrReturn = sr2.ReadChars(chArr.Length );
iCountTestcases++;
//.........这里部分代码省略.........
示例14: GetGuesses
} // end method DisplayMessage
// set up connection for client to play Hangman
public void GetGuesses()
{
// start listening for connections
IPAddress local = IPAddress.Parse( "127.0.0.1" );
TcpListener listener = new TcpListener( local, 50000 );
listener.Start();
// accept client connection and get NetworkStream to
// communicate with client
Socket connection = listener.AcceptSocket();
DisplayMessage( "Connection received\r\n" );
NetworkStream socketStream = new NetworkStream( connection );
// create reader and writer for client
BinaryWriter writer = new BinaryWriter( socketStream );
BinaryReader reader = new BinaryReader( socketStream );
// choose random word
Random randomWord = new Random();
int wordNumber = randomWord.Next( 25 );
string word = "";
// open word file
StreamReader wordReader = new StreamReader( "words.txt" );
// find word in file
for ( int i = 0; i <= wordNumber; i++ )
word = wordReader.ReadLine();
// display word and send length of word to client
DisplayMessage( "The secret word is: " + word + "\r\n" );
writer.Write( word.Length );
// initialize Hangman game variables
int numberWrong = 0, numberLettersLeft = word.Length,
numberCharsInWord = 0;
char guess;
// while entire word has not been guessed and
// user has not made 5 mistakes, process user guesses
while ( numberLettersLeft > 0 && numberWrong < 5 )
{
numberCharsInWord = 0;
// get guess
guess = reader.ReadChar();
DisplayMessage( "The user guessed: " + guess + "\r\n" );
// find out how many occurrences of letter in word
for ( int i = 0; i < word.Length; i++ )
if ( word[ i ] == guess )
numberCharsInWord++;
// send client number of occurrences
writer.Write( numberCharsInWord );
// if the character is present, send index values
// of each occurrence
if ( numberCharsInWord != 0 )
{
for ( int i = 0; i < word.Length; i++ )
{
if ( word[ i ] == guess )
{
writer.Write( i );
// decrement number of letters left to guess
numberLettersLeft--;
} // end if
} // end for
} // end if
else
numberWrong++; // user made mistake, add 1 to number wrong
} // end while
// if word not guessed and user made 5 mistakes,
// tell user the word
if ( numberLettersLeft != 0 && numberWrong == 5 )
writer.Write( word );
// close connections
connection.Close();
socketStream.Close();
reader.Close();
writer.Close();
} // end method GetGuesses
示例15: ReadDBF
// Read an entire standard DBF file into a DataTable
public static DataTable ReadDBF(string dbfFile)
{
long start = DateTime.Now.Ticks;
DataTable dt = new DataTable();
BinaryReader recReader;
string number;
string year;
string month;
string day;
long lDate;
long lTime;
DataRow row;
int fieldIndex;
// If there isn't even a file, just return an empty DataTable
if ((false == File.Exists(dbfFile)))
{
return dt;
}
BinaryReader br = null;
try
{
// Read the header into a buffer
br = new BinaryReader(File.OpenRead(dbfFile));
byte[] buffer = br.ReadBytes(Marshal.SizeOf(typeof(DBFHeader)));
// Marshall the header into a DBFHeader structure
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
DBFHeader header = (DBFHeader) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(DBFHeader));
handle.Free();
// Read in all the field descriptors. Per the spec, 13 (0D) marks the end of the field descriptors
ArrayList fields = new ArrayList();
while ((13 != br.PeekChar()))
{
buffer = br.ReadBytes(Marshal.SizeOf(typeof(FieldDescriptor)));
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
fields.Add((FieldDescriptor)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(FieldDescriptor)));
handle.Free();
}
// Read in the first row of records, we need this to help determine column types below
((FileStream) br.BaseStream).Seek(header.headerLen + 1, SeekOrigin.Begin);
buffer = br.ReadBytes(header.recordLen);
recReader = new BinaryReader(new MemoryStream(buffer));
// Create the columns in our new DataTable
DataColumn col = null;
foreach (FieldDescriptor field in fields)
{
number = Encoding.ASCII.GetString(recReader.ReadBytes(field.fieldLen));
switch (field.fieldType)
{
case 'N':
if (number.IndexOf(".") > -1)
{
col = new DataColumn(field.fieldName, typeof(decimal));
}
else
{
col = new DataColumn(field.fieldName, typeof(int));
}
break;
case 'C':
col = new DataColumn(field.fieldName, typeof(string));
break;
case 'T':
// You can uncomment this to see the time component in the grid
//col = new DataColumn(field.fieldName, typeof(string));
col = new DataColumn(field.fieldName, typeof(DateTime));
break;
case 'D':
col = new DataColumn(field.fieldName, typeof(DateTime));
break;
case 'L':
col = new DataColumn(field.fieldName, typeof(bool));
break;
case 'F':
col = new DataColumn(field.fieldName, typeof(Double));
break;
}
dt.Columns.Add(col);
}
// Skip past the end of the header.
((FileStream) br.BaseStream).Seek(header.headerLen, SeekOrigin.Begin);
// Read in all the records
for (int counter = 0; counter <= header.numRecords - 1; counter++)
{
// First we'll read the entire record into a buffer and then read each field from the buffer
// This helps account for any extra space at the end of each record and probably performs better
buffer = br.ReadBytes(header.recordLen);
recReader = new BinaryReader(new MemoryStream(buffer));
// All dbf field records begin with a deleted flag field. Deleted - 0x2A (asterisk) else 0x20 (space)
if (recReader.ReadChar() == '*')
{
//.........这里部分代码省略.........