Csharp/C Sharp/File Stream/File Read Write — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 11:45, 26 мая 2010
Содержание
- 1 Copy a file
- 2 Demonstrate random access
- 3 Demonstrates opening/creating a file for writing and truncating its length to 0 bytes.
- 4 Demonstrates seeking to a position in a file from the end
- 5 Display a text file
- 6 Hex value Dump
- 7 Writes the same string to a file and to the screen using a common method
- 8 Write to a file
Copy a file
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/* Copy a file.
To use this program, specify the name
of the source file and the destination file.
For example, to copy a file called FIRST.DAT
to a file called SECOND.DAT, use the following
command line.
CopyFile FIRST.DAT SECOND.DAT
*/
using System;
using System.IO;
public class CopyFile {
public static void Main(string[] args) {
int i;
FileStream fin;
FileStream fout;
try {
// open input file
try {
fin = new FileStream(args[0], FileMode.Open);
} catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message + "\nInput File Not Found");
return;
}
// open output file
try {
fout = new FileStream(args[1], FileMode.Create);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "\nError Opening Output File");
return;
}
} catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message + "\nUsage: CopyFile From To");
return;
}
// Copy File
try {
do {
i = fin.ReadByte();
if(i != -1) fout.WriteByte((byte)i);
} while(i != -1);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "File Error");
}
fin.Close();
fout.Close();
}
}
Demonstrate random access
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate random access.
using System;
using System.IO;
public class RandomAccessDemo {
public static void Main() {
FileStream f;
char ch;
try {
f = new FileStream("random.dat", FileMode.Create);
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
return ;
}
// Write the alphabet.
for(int i=0; i < 26; i++) {
try {
f.WriteByte((byte)("A"+i));
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
return ;
}
}
try {
// Now, read back specific values
f.Seek(0, SeekOrigin.Begin); // seek to first byte
ch = (char) f.ReadByte();
Console.WriteLine("First value is " + ch);
f.Seek(1, SeekOrigin.Begin); // seek to second byte
ch = (char) f.ReadByte();
Console.WriteLine("Second value is " + ch);
f.Seek(4, SeekOrigin.Begin); // seek to 5th byte
ch = (char) f.ReadByte();
Console.WriteLine("Fifth value is " + ch);
Console.WriteLine();
// Now, read every other value.
Console.WriteLine("Here is every other value: ");
for(int i=0; i < 26; i += 2) {
f.Seek(i, SeekOrigin.Begin); // seek to ith double
ch = (char) f.ReadByte();
Console.Write(ch + " ");
}
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
}
Console.WriteLine();
f.Close();
}
}
Demonstrates opening/creating a file for writing and truncating its length to 0 bytes.
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// StrmWrit.cs -- Demonstrates opening/creating a file for writing and truncating
// its length to 0 bytes.
// Compile this program with the following command line:
// C:>csc StrmWrit.cs
using System;
using System.IO;
namespace nsStreams
{
public class StrmWrit
{
static public void Main ()
{
FileStream strm;
// Open or create the file for writing
try
{
strm = new FileStream ("./write.txt", FileMode.OpenOrCreate, FileAccess.Write);
}
// If the open fails, the constructor will throw an exception.
catch (Exception e)
{
Console.WriteLine (e.Message);
Console.WriteLine ("Cannot open write.txt for writing");
return;
}
// Truncate the file using the SetLength() method.
strm.SetLength (0);
Console.WriteLine ("Enter text. Type a blank line to exit\r\n");
// Accept text from the keyboard and write it to the file.
while (true)
{
string str = Console.ReadLine ();
if (str.Length == 0)
break;
byte [] b; // = new byte [str.Length];
StringToByte (str, out b);
strm.Write (b, 0, b.Length);
}
Console.WriteLine ("Text written to write.txt");
// Close the stream
strm.Close ();
}
//
// Convert a string to a byte array, adding a carriage return/line feed to it
static protected void StringToByte (string str, out byte [] b)
{
b = new byte [str.Length + 2];
int x;
for (x = 0; x < str.Length; ++x)
{
b[x] = (byte) str[x];
}
// Add a carriage return/line feed
b[x] = 13;
b[x + 1] = 10;
}
}
}
Demonstrates seeking to a position in a file from the end
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Seek.cs -- Demonstrates seeking to a position in a file from the end,
// middle and beginning of a file
//
// Compile this program with the following command line:
// C:>csc Seek.cs
using System;
using System.IO;
using System.Text;
namespace nsStreams
{
public class Seek
{
const string str1 = "Now is the time for all good men to " +
"come to the aid of their Teletype.\r\n";
const string str2 = "The quick red fox jumps over the " +
"lazy brown dog.\r\n";
static public void Main ()
{
FileStream strm;
try
{
strm = new FileStream ("./StrmSeek.txt",
FileMode.Create,
FileAccess.ReadWrite);
}
catch (Exception e)
{
Console.WriteLine (e);
Console.WriteLine ("Cannot open StrmSeek.txt " +
"for reading and writing");
return;
}
// Clear out any remnants in the file
// strm.SetLength (0);
foreach (char ch in str1)
{
strm.WriteByte ((byte) ch);
}
foreach (char ch in str2)
{
strm.WriteByte ((byte) ch);
}
// Seek from the beginning of the file
strm.Seek (str1.Length, SeekOrigin.Begin);
// Read 17 bytes and write to the console.
byte [] text = new byte [17];
strm.Read (text, 0, text.Length);
ShowText (text);
// Seek back 17 bytes and reread.
strm.Seek (-17, SeekOrigin.Current);
strm.Read (text, 0, text.Length);
ShowText (text);
// Seek from the end of the file to the beginning of the second line.
strm.Seek (-str2.Length, SeekOrigin.End);
strm.Read (text, 0, text.Length);
ShowText (text);
}
static void ShowText (byte [] text)
{
StringBuilder str = new StringBuilder (text.Length);
foreach (byte b in text)
{
str.Append ((char) b);
}
Console.WriteLine (str);
}
}
}
//File: StrmSeek.txt
/*
Now is the time for all good men to come to the aid of their Teletype.
The quick red fox jumps over the lazy brown dog.
*/
Display a text file
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/* Display a text file.
To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.CS,
use the following command line.
ShowFile TEST.CS
*/
using System;
using System.IO;
public class ShowFile {
public static void Main(string[] args) {
int i;
FileStream fin;
try {
fin = new FileStream(args[0], FileMode.Open);
} catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message);
return;
} catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message + "\nUsage: ShowFile File");
return;
}
// read bytes until EOF is encountered
do {
try {
i = fin.ReadByte();
} catch(Exception exc) {
Console.WriteLine(exc.Message);
return;
}
if(i != -1) Console.Write((char) i);
} while(i != -1);
fin.Close();
}
}
Hex value Dump
using System;
using System.IO;
class HexDump {
public static void Main(string[] astrArgs) {
Stream stream = new FileStream("c:\\a.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] abyBuffer = new byte[16];
long lAddress = 0;
int count;
while ((count = stream.Read(abyBuffer, 0, 16)) > 0) {
ComposeLine(lAddress, abyBuffer, count);
lAddress += 16;
}
}
public static void ComposeLine(long lAddress, byte[] abyBuffer, int count) {
Console.WriteLine(String.Format("{0:X4}-{1:X4} ", (uint)lAddress / 65536, (ushort)lAddress));
for (int i = 0; i < 16; i++) {
Console.WriteLine((i < count) ? String.Format("{0:X2}", abyBuffer[i]) : " ");
Console.WriteLine((i == 7 && count > 7) ? "-" : " ");
}
Console.WriteLine(" ");
for (int i = 0; i < 16; i++) {
char ch = (i < count) ? Convert.ToChar(abyBuffer[i]) : " ";
Console.WriteLine(Char.IsControl(ch) ? "." : ch.ToString());
}
}
}
Writes the same string to a file and to the screen using a common method
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// WriteOut.cs -- Writes the same string to a file and to the screen using
// a common method.
//
// Compile this program with the following command line:
// C:>csc WriteOut.cs
namespace nsStreams
{
using System;
// When using streams, you must declare that you are using System.IO
using System.IO;
public class WriteOut
{
static public void Main ()
{
string str = "This is a line of text\r\n";
// Open the standard output stream
Stream ostrm = Console.OpenStandardOutput ();
// Open a file. You should protect an open in a try ... catch block
FileStream fstrm;
try
{
fstrm = new FileStream ("./OutFile.txt", FileMode.OpenOrCreate);
}
catch
{
Console.WriteLine ("Failed to open file");
return;
}
// Call WriteToStream() to write the same string to both
WriteToStream (ostrm, str);
WriteToStream (fstrm, str);
// Close the file.
fstrm.Close ();
ostrm.Close ();
}
static public void WriteToStream (Stream strm, string text)
{
foreach (char ch in text)
{
strm.WriteByte ((Byte) ch);
}
// Flush the output to make it write
strm.Flush ();
}
}
}
Write to a file
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Write to a file.
using System;
using System.IO;
public class WriteToFile {
public static void Main(string[] args) {
FileStream fout;
// open output file
try {
fout = new FileStream("test.txt", FileMode.Create);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "\nError Opening Output File");
return;
}
// Write the alphabet to the file.
try {
for(char c = "A"; c <= "Z"; c++)
fout.WriteByte((byte) c);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "File Error");
}
fout.Close();
}
}