Csharp/C Sharp/File Stream/Binary Read Write — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 11:45, 26 мая 2010
Содержание
- 1 BinaryWriter and BinaryReader classes for the writing and reading of primitive types
- 2 Binary Writer Reader
- 3 Creating a sequential-access file
- 4 File pointer move and read binary file
- 5 new BinaryReader(stream)
- 6 new BinaryWriter(stream) and Write method
- 7 Read and Write a Binary File
- 8 Reading a sequential-access file
- 9 Read the data from a file and desiralize it
- 10 StreamWriter and BinaryWriter
- 11 Use BinaryReader and BinaryWriter to implement a simple inventory program
- 12 Working with the BinaryReader Class
- 13 Working with the BinaryWriter Class
- 14 Write and then read back binary data
BinaryWriter and BinaryReader classes for the writing and reading of primitive types
using System;
using System.IO;
public class Binary {
public static void Main(string [] args) {
BinaryWriter output = new BinaryWriter(new FileStream("test.dat",FileMode.Create));
output.Write(1);
output.Write(0.01);
output.Close();
BinaryReader input = new BinaryReader(new FileStream("test.dat",FileMode.Open));
Console.WriteLine("{0} ", input.ReadInt32());
Console.WriteLine("{0:F1} ", input.ReadDouble());
input.Close();
}
}
Binary Writer Reader
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
class Program {
static void Main(string[] args) {
FileInfo f = new FileInfo("BinFile.dat");
BinaryWriter bw = new BinaryWriter(f.OpenWrite());
Console.WriteLine("Base stream is: {0}", bw.BaseStream);
double aDouble = 1234.67;
int anInt = 34567;
char[] aCharArray = { "A", "B", "C" };
bw.Write(aDouble);
bw.Write(anInt);
bw.Write(aCharArray);
bw.Close();
BinaryReader br = new BinaryReader(f.OpenRead());
int temp = 0;
while (br.PeekChar() != -1) {
Console.Write("{0,7:x} ", br.ReadByte());
if (++temp == 4) {
Console.WriteLine();
temp = 0;
}
}
}
}
Creating a sequential-access file
using System;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class CreateFile {
static void Main() {
BinaryFormatter formatter = new BinaryFormatter();
FileStream output = new FileStream( "test.dat",FileMode.OpenOrCreate, FileAccess.Write );
Record record = new Record();
record.Account = 1234;
record.FirstName = "FirstName";
record.LastName = "LastName";
record.Balance = 1234.345;
formatter.Serialize( output, record );
output.Close();
}
}
[Serializable]
public class Record{
public int Account;
public String FirstName;
public String LastName;
public double Balance;
}
File pointer move and read binary file
using System;
using System.IO;
using System.Text;
class Class1{
static void Main(string[] args) {
byte[] byData = new byte[100];
char[] charData = new Char[100];
try {
FileStream aFile = new FileStream("practice.txt",FileMode.Open);
aFile.Seek(55,SeekOrigin.Begin);
aFile.Read(byData,0,100);
}
catch(IOException e)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(byData, 0, byData.Length, charData, 0);
Console.WriteLine(charData);
return;
}
}
new BinaryReader(stream)
using System;
using System.IO;
class MainClass
{
public static byte[] DecimalToByteArray (decimal src){
using (MemoryStream stream = new MemoryStream()) {
using (BinaryWriter writer = new BinaryWriter(stream)){
writer.Write(src);
return stream.ToArray();
}
}
}
public static decimal ByteArrayToDecimal (byte[] src){
using (MemoryStream stream = new MemoryStream(src)){
using (BinaryReader reader = new BinaryReader(stream)){
return reader.ReadDecimal();
}
}
}
public static void Main()
{
byte[] b = null;
b = BitConverter.GetBytes(true);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(BitConverter.ToBoolean(b, 0));
b = BitConverter.GetBytes(3678);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(BitConverter.ToInt32(b, 0));
b = DecimalToByteArray(285998345545.563846696m);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(ByteArrayToDecimal(b));
}
}
new BinaryWriter(stream) and Write method
using System;
using System.IO;
class MainClass
{
public static byte[] DecimalToByteArray (decimal src){
using (MemoryStream stream = new MemoryStream()) {
using (BinaryWriter writer = new BinaryWriter(stream)){
writer.Write(src);
return stream.ToArray();
}
}
}
public static decimal ByteArrayToDecimal (byte[] src){
using (MemoryStream stream = new MemoryStream(src)){
using (BinaryReader reader = new BinaryReader(stream)){
return reader.ReadDecimal();
}
}
}
public static void Main()
{
byte[] b = null;
b = BitConverter.GetBytes(true);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(BitConverter.ToBoolean(b, 0));
b = BitConverter.GetBytes(3678);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(BitConverter.ToInt32(b, 0));
b = DecimalToByteArray(12345678.123456m);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(ByteArrayToDecimal(b));
}
}
Read and Write a Binary File
using System;
using System.IO;
public class BinaryFileTest {
private static void Main() {
FileStream fs = new FileStream("test.dat", FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);
w.Write(1.2M);
w.Write("string");
w.Write("string 2");
w.Write("!");
w.Flush();
w.Close();
fs.Close();
fs = new FileStream("test.dat", FileMode.Open);
StreamReader sr = new StreamReader(fs);
Console.WriteLine(sr.ReadToEnd());
fs.Position = 0;
BinaryReader br = new BinaryReader(fs);
Console.WriteLine(br.ReadDecimal());
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadChar());
fs.Close();
}
}
Reading a sequential-access file
using System;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class CreateFile {
static void Main() {
BinaryFormatter formatter = new BinaryFormatter();
FileStream output = new FileStream( "test.dat",FileMode.OpenOrCreate, FileAccess.Write );
Record record = new Record();
record.Account = 1234;
record.FirstName = "FirstName";
record.LastName = "LastName";
record.Balance = 1234.345;
formatter.Serialize( output, record );
output.Close();
BinaryFormatter reader = new BinaryFormatter();
FileStream input = new FileStream( "test.dat", FileMode.Open, FileAccess.Read );
Record record1 =( Record )reader.Deserialize( input );
Console.WriteLine(record1.FirstName);
}
}
[Serializable]
public class Record{
public int Account;
public String FirstName;
public String LastName;
public double Balance;
}
Read the data from a file and desiralize it
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Client.Chapter_11___File_and_Streams
{
public class Class1Chapter_11___File_and_Streams {
[STAThread]
static void Main(string[] args)
{
Point p1 = new Point();
p1.xpoint = 0x1111;
p1.ypoint = 0x2222;
// Opens a file and serializes the object into it.
Stream stream = File.Open("onepoint.bin", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, p1);
stream.Close();
//Read the data from a file and desiralize it
Stream openStream = File.Open("onepoint.bin", FileMode.Open);
Point desierializedPoint = new Point();
desierializedPoint = (Point)bformatter.Deserialize(openStream);
}
}
[Serializable()]
class Point
{
public int xpoint;
public int ypoint;
}
}
StreamWriter and BinaryWriter
using System;
using System.IO;
class BinReadWriteApp
{
static void Main(string[] args)
{
Stream s = new FileStream("Foo.txt", FileMode.Create);
StreamWriter w = new StreamWriter(s);
w.Write("Hello World ");
w.Write(123);
w.Write(" ");
w.Write(45.67);
w.Close();
s.Close();
Stream t = new FileStream("Bar.dat", FileMode.Create);
BinaryWriter b = new BinaryWriter(t);
b.Write("Hello World ");
b.Write(123);
b.Write(" ");
b.Write(45.67);
b.Close();
t.Close();
}
}
Use BinaryReader and BinaryWriter to implement a simple inventory program
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/* Use BinaryReader and BinaryWriter to implement
a simple inventory program. */
using System;
using System.IO;
public class Inventory {
public static void Main() {
BinaryWriter dataOut;
BinaryReader dataIn;
string item; // name of item
int onhand; // number on hand
double cost; // cost
try {
dataOut = new
BinaryWriter(new FileStream("inventory.dat",
FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "\nCannot open file.");
return;
}
// Write some inventory data to the file.
try {
dataOut.Write("Hammers");
dataOut.Write(10);
dataOut.Write(3.95);
dataOut.Write("Screwdrivers");
dataOut.Write(18);
dataOut.Write(1.50);
dataOut.Write("Pliers");
dataOut.Write(5);
dataOut.Write(4.95);
dataOut.Write("Saws");
dataOut.Write(8);
dataOut.Write(8.95);
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "\nWrite error.");
}
dataOut.Close();
Console.WriteLine();
// Now, open inventory file for reading.
try {
dataIn = new
BinaryReader(new FileStream("inventory.dat",
FileMode.Open));
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message + "\nCannot open file.");
return;
}
// Lookup item entered by user.
Console.Write("Enter item to lookup: ");
string what = Console.ReadLine();
Console.WriteLine();
try {
for(;;) {
// Read an inventory entry.
item = dataIn.ReadString();
onhand = dataIn.ReadInt32();
cost = dataIn.ReadDouble();
/* See if the item matches the one requested.
If so, display information */
if(item.rupareTo(what) == 0) {
Console.WriteLine(onhand + " " + item + " on hand. " +
"Cost: {0:C} each", cost);
Console.WriteLine("Total value of {0}: {1:C}." ,
item, cost * onhand);
break;
}
}
}
catch(EndOfStreamException) {
Console.WriteLine("Item not found.");
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "Read error.");
}
dataIn.Close();
}
}
Working with the BinaryReader Class
using System;
using System.IO;
class MainClass {
static public void Main() {
FileStream BinaryFile = new FileStream("test.dat", FileMode.Create, FileAccess.ReadWrite);
BinaryReader Reader = new BinaryReader(BinaryFile);
BinaryWriter Writer = new BinaryWriter(BinaryFile);
Writer.Write("a");
Writer.Write(123);
Writer.Write(456.789);
Writer.Write("test string");
char ReadCharacter;
double ReadDouble;
int ReadInteger;
string ReadString;
BinaryFile.Seek(0, SeekOrigin.Begin);
ReadCharacter = Reader.ReadChar();
ReadInteger = Reader.ReadInt32();
ReadDouble = Reader.ReadDouble();
ReadString = Reader.ReadString();
Console.WriteLine("Character: {0}", ReadCharacter);
Console.WriteLine("Integer: {0}", ReadInteger);
Console.WriteLine("Double: {0}", ReadDouble);
Console.WriteLine("String: {0}", ReadString);
}
}
Working with the BinaryWriter Class
using System;
using System.IO;
class MainClass
{
static public void Main()
{
FileStream BinaryFile = new FileStream("test.dat", FileMode.Create, FileAccess.ReadWrite);
BinaryWriter Writer = new BinaryWriter(BinaryFile);
Writer.Write("a");
Writer.Write(123);
Writer.Write(456.789);
Writer.Write("test string");
}
}
Write and then read back binary data
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Write and then read back binary data.
using System;
using System.IO;
public class RWData {
public static void Main() {
BinaryWriter dataOut;
BinaryReader dataIn;
int i = 10;
double d = 1023.56;
bool b = true;
try {
dataOut = new
BinaryWriter(new FileStream("testdata", FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "\nCannot open file.");
return;
}
try {
Console.WriteLine("Writing " + i);
dataOut.Write(i);
Console.WriteLine("Writing " + d);
dataOut.Write(d);
Console.WriteLine("Writing " + b);
dataOut.Write(b);
Console.WriteLine("Writing " + 12.2 * 7.4);
dataOut.Write(12.2 * 7.4);
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "\nWrite error.");
}
dataOut.Close();
Console.WriteLine();
// Now, read them back.
try {
dataIn = new
BinaryReader(new FileStream("testdata", FileMode.Open));
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message + "\nCannot open file.");
return;
}
try {
i = dataIn.ReadInt32();
Console.WriteLine("Reading " + i);
d = dataIn.ReadDouble();
Console.WriteLine("Reading " + d);
b = dataIn.ReadBoolean();
Console.WriteLine("Reading " + b);
d = dataIn.ReadDouble();
Console.WriteLine("Reading " + d);
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "Read error.");
}
dataIn.Close();
}
}