Csharp/C Sharp/File Stream/FileStream — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 14:45, 26 мая 2010
Содержание
- 1 An enhanced cipher component that maintains a log file
- 2 A simple disk-to-screen utility that demonstrates a FileReader
- 3 Compare two files
- 4 Create a file stream with new FileStream("test.bin", FileMode.Create)
- 5 Create StreamReader from File Stream
- 6 FileStream with FileMode.Create and FileMode.Open
- 7 illustrates reading and writing binary data
- 8 illustrates use of FileStreams
- 9 illustrates use of FileStreams 2
- 10 Reading and Writing Files
- 11 Reads lines separated by vertical bars
- 12 Reads strings from a file created in a text editor
- 13 Seek from Begin
- 14 Set File IO Permission to c:
- 15 Using FileStreams
- 16 Write byte array to a file
An enhanced cipher component that maintains a log file
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// An enhanced cipher component that maintains a log file. using CipherLib; // import CipherComp"s namespace
using System; using System.ruponentModel; using System.IO;
namespace CipherLib {
// An Cipher component that maintains a log file. class CipherComp : Component { static int useID = 0; int id; // instance id bool isDisposed; // true if component is disposed. FileStream log; // Constructor public CipherComp() { isDisposed = false; // component not disposed try { log = new FileStream("CipherLog" + useID, FileMode.Create); id = useID; useID++; } catch (FileNotFoundException exc) { Console.WriteLine(exc); log = null; } } // Destructor ~CipherComp() { Console.WriteLine("Destructor for component " + id); Dispose(false); } // Encode the file. Return and store result. public string Encode(string msg) { string temp = ""; for(int i=0;i < msg.Length; i++) temp += (char) (msg[i] + 1); // Store in log file. for(int i=0; i < temp.Length; i++) log.WriteByte((byte) temp[i]); return temp; } // Decode the message. Return and store result. public string Decode(string msg) { string temp = ""; for(int i=0; i < msg.Length; i++) temp += (char) (msg[i] - 1); // Store in log file. for(int i=0; i < temp.Length; i++) log.WriteByte((byte) temp[i]); return temp; } protected override void Dispose(bool dispAll) { Console.WriteLine("Dispose(" + dispAll + ") for component " + id); if(!isDisposed) { if(dispAll) { Console.WriteLine("Closing file for " + "component " + id); log.Close(); // close encoded file isDisposed = true; } // no unmanaged resources to release base.Dispose(dispAll); } } }
} // Another client that uses CipherComp.
public class CipherCompClient1 {
public static void Main() { CipherComp cc = new CipherComp(); string text = "Testing"; string ciphertext = cc.Encode(text); Console.WriteLine(ciphertext); string plaintext = cc.Decode(ciphertext); Console.WriteLine(plaintext); text = "Components are powerful."; ciphertext = cc.Encode(text); Console.WriteLine(ciphertext); plaintext = cc.Decode(ciphertext); Console.WriteLine(plaintext); cc.Dispose(); // free resources }
}
</source>
A simple disk-to-screen utility that demonstrates a FileReader
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
/* A simple disk-to-screen utility that
demonstrates a FileReader. */
using System; using System.IO;
public class DtoS {
public static void Main() { FileStream fin; string s; try { fin = new FileStream("test.txt", FileMode.Open); } catch(FileNotFoundException exc) { Console.WriteLine(exc.Message + "Cannot open file."); return ; } StreamReader fstr_in = new StreamReader(fin); // Read the file line-by-line. while((s = fstr_in.ReadLine()) != null) { Console.WriteLine(s); } fstr_in.Close(); }
}
</source>
Compare two files
<source lang="csharp"> /* C# A Beginner"s Guide By Schildt Publisher: Osborne McGraw-Hill ISBN: 0072133295
- /
/*
Project 11-1 Compare two files. To use this program, specify the names of the files to be compared on the command line. For example: CompFile FIRST.TXT SECOND.TXT
- /
using System; using System.IO;
public class CompFiles {
public static void Main(string[] args) { int i=0, j=0; FileStream f1; FileStream f2; try { // open first file try { f1 = new FileStream(args[0], FileMode.Open); } catch(FileNotFoundException exc) { Console.WriteLine(exc.Message); return; } // open second file try { f2 = new FileStream(args[1], FileMode.Open); } catch(FileNotFoundException exc) { Console.WriteLine(exc.Message); return; } } catch(IndexOutOfRangeException exc) { Console.WriteLine(exc.Message + "\nUsage: CompFile f1 f2"); return; } // Compare files try { do { i = f1.ReadByte(); j = f2.ReadByte(); if(i != j) break; } while(i != -1 && j != -1); } catch(IOException exc) { Console.WriteLine(exc.Message); } if(i != j) Console.WriteLine("Files differ."); else Console.WriteLine("Files are the same."); f1.Close(); f2.Close(); }
}
</source>
Create a file stream with new FileStream("test.bin", FileMode.Create)
<source lang="csharp"> using System; using System.IO; class MainClass {
static void Main() { using (FileStream fs = new FileStream("test.bin", FileMode.Create)) { using (BinaryWriter w = new BinaryWriter(fs)) { w.Write(124.23M); w.Write("Tstring"); w.Write("Tstring 2"); w.Write("!"); } } Console.WriteLine("Press Enter to read the information."); Console.ReadLine(); using (FileStream fs = new FileStream("test.bin", FileMode.Open)) { using (StreamReader sr = new StreamReader(fs)) { Console.WriteLine(sr.ReadToEnd()); Console.WriteLine(); fs.Position = 0; using (BinaryReader br = new BinaryReader(fs)) { Console.WriteLine(br.ReadDecimal()); Console.WriteLine(br.ReadString()); Console.WriteLine(br.ReadString()); Console.WriteLine(br.ReadChar()); } } } }
}
</source>
Create StreamReader from File Stream
<source lang="csharp"> using System; using System.IO; public class IOExample {
static void Main() { FileStream fs; StreamReader srIn; try { fs = new FileStream("practice.txt", FileMode.Open ); srIn = new StreamReader(fs); string line = srIn.ReadLine(); Console.WriteLine("line = "+line); srIn.Close(); } catch (IOException ioe) { Console.WriteLine("IOException occurred: "+ioe.Message); } }
}
</source>
FileStream with FileMode.Create and FileMode.Open
<source lang="csharp"> using System; using System.IO; using System.Text; class MainClass {
static void Main() { using (FileStream fs = new FileStream("test.txt", FileMode.Create)) { using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) { w.WriteLine(124.23M); w.WriteLine("Test string"); w.WriteLine("!"); } } Console.WriteLine("Press Enter to read the information."); Console.ReadLine(); // Open the file in read-only mode. using (FileStream fs = new FileStream("test.txt", FileMode.Open)) { using (StreamReader r = new StreamReader(fs, Encoding.UTF8)) { // Read the data and convert it to the appropriate data type. Console.WriteLine(Decimal.Parse(r.ReadLine())); Console.WriteLine(r.ReadLine()); Console.WriteLine(Char.Parse(r.ReadLine())); } } }
}
</source>
illustrates reading and writing binary data
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/* Example15_15.cs illustrates reading and writing binary data
- /
using System; using System.IO; public class Example15_15 {
public static void Main() { // create a new file to work with FileStream outStream = File.Create("c:\\BinaryTest.dat"); // use a BinaryWriter to write formatted data to the file BinaryWriter bw = new BinaryWriter(outStream); // write various data to the file bw.Write( (int) 32); bw.Write( (decimal) 4.567); string s = "Test String"; bw.Write(s); // flush and close bw.Flush(); bw.Close(); // now open the file for reading FileStream inStream = File.OpenRead("c:\\BinaryTest.dat"); // use a BinaryReader to read formatted data and dump it to the screen BinaryReader br = new BinaryReader(inStream); int i = br.ReadInt32(); decimal d = br.ReadDecimal(); string s2 = br.ReadString(); Console.WriteLine(i); Console.WriteLine(d); Console.WriteLine(s2); // clean up br.Close(); }
}
</source>
illustrates use of FileStreams
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/* Example15_10.cs illustrates use of FileStreams
- /
using System; using System.Windows.Forms; using System.IO; public class Example15_10 {
[STAThread] public static void Main() { // use an open file dialog to get a filename OpenFileDialog dlgOpen = new OpenFileDialog(); dlgOpen.Title="Select file to back up"; if (dlgOpen.ShowDialog() == DialogResult.OK) { FileStream inStream = File.OpenRead(dlgOpen.FileName); FileStream outStream = File.OpenWrite(dlgOpen.FileName + ".bak"); int b; // copy all data from in to out while ((b = inStream.ReadByte()) > -1) outStream.WriteByte( (byte) b); // clean up outStream.Flush(); outStream.Close(); inStream.Close(); } }
}
</source>
illustrates use of FileStreams 2
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/* Example15_11.cs illustrates use of FileStreams
- /
using System; using System.Windows.Forms; using System.IO; public class Example15_11 {
[STAThread] public static void Main() { // use an open file dialog to get a filename OpenFileDialog dlgOpen = new OpenFileDialog(); dlgOpen.Title="Select file to back up"; if (dlgOpen.ShowDialog() == DialogResult.OK) { FileStream inStream = File.OpenRead(dlgOpen.FileName); FileStream outStream = File.OpenWrite(dlgOpen.FileName + ".bak"); byte[] buf = new byte[4096]; int bytesRead; // copy all data from in to out while ((bytesRead = inStream.Read(buf, 0, 4096)) > 0) outStream.Write(buf, 0, bytesRead); // clean up outStream.Flush(); outStream.Close(); inStream.Close(); } }
}
</source>
Reading and Writing Files
<source lang="csharp"> using System; using System.IO; public class ReadingWritingFiles {
public static void Main() { FileStream f = new FileStream("output.txt", FileMode.Create); StreamWriter s = new StreamWriter(f); s.WriteLine("{0} {1}", "test", 55); s.Close(); f.Close(); }
}
</source>
Reads lines separated by vertical bars
<source lang="csharp"> using System; using System.IO; public class FileReadAddresses {
public static void Main( ) { String line; String street, city, state, zip; StreamReader f = new StreamReader("test.data"); while ((line=f.ReadLine())!= null){ String[] strings = line.Split(new char[]{"|"}); if (strings.Length == 4) { street = strings[0]; city = strings[1]; state = strings[2]; zip = strings[3]; Console.WriteLine(street); Console.WriteLine(city); Console.WriteLine(state); Console.WriteLine(zip); } } f.Close(); }
} //File: test.data /* 4665 Street|Toronto|ON|90048
- /
</source>
Reads strings from a file created in a text editor
<source lang="csharp"> using System; using System.IO; public class FileReadStrings {
public static void Main( ) { String line; StreamReader f = new StreamReader("test.data"); while((line=f.ReadLine()) != null) Console.WriteLine(line); f.Close(); }
} //File: test.data /* 4665 Street|Toronto|ON|90048
- /
</source>
Seek from Begin
<source lang="csharp">
using System; using System.Collections.Generic; using System.Text; using System.IO;
class Program {
static void Main(string[] args) { byte[] byData = new byte[200]; char[] charData = new Char[200]; try { FileStream aFile = new FileStream("Program.cs", FileMode.Open); aFile.Seek(135, SeekOrigin.Begin); aFile.Read(byData, 0, 200); } catch (IOException e) { Console.WriteLine("An IO exception has been thrown!"); Console.WriteLine(e.ToString()); Console.ReadKey(); return; } Decoder d = Encoding.UTF8.GetDecoder(); d.GetChars(byData, 0, byData.Length, charData, 0); Console.WriteLine(charData); }
}
</source>
Set File IO Permission to c:
<source lang="csharp"> using System; using System.Collections.Generic; using System.Text; using System.Security.Permissions;
class Program {
static void Main(string[] args) { MyClass.Method(); }
} [FileIOPermission(SecurityAction.Assert, Read = "C:/")] class MyClass {
public static void Method() { // implementation goes here }
}
</source>
Using FileStreams
<source lang="csharp"> /*
* 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; namespace Client.Chapter_11___File_and_Streams {
public class UsingFileStreams { static void Main(string[] args) { //Creates a file with read-write access that allows others to read FileStream MyFileStream1 = new FileStream(@"c:\Projects\Testing.txt", FileMode.Create); FileInfo MyFiles = new FileInfo(@"c:\Projects\Testing.txt"); FileStream MyFileStream2 = MyFiles.OpenRead(); //or any of the following MyFileStream2 = MyFiles.OpenWrite(); MyFileStream2 = MyFiles.Open(FileMode.Append, FileAccess.Read, FileShare.None); MyFileStream2 = MyFiles.Create(); //You can read file stream ona pe byte basis or as an array of bytes int MyBytes = MyFileStream1.ReadByte(); //or int NumberOfBytes = 200; byte[] MyByteArray = new Byte[NumberOfBytes]; int BytesRead = MyFileStream1.Read(MyByteArray, 0, NumberOfBytes); //Data can be written to FileStreams as well through bytes or arrays of //bytes byte MyWriteByte = 100; MyFileStream1.WriteByte(MyWriteByte); //or via an array int NumberOfBytesToWrite = 256; byte[] MyWriteByteArray = new Byte[NumberOfBytesToWrite]; for (int i = 0; i < 256; i++) { MyWriteByteArray[i] = (byte)i; i++; } MyFileStream1.Write(MyWriteByteArray, 0, NumberOfBytesToWrite); MyFileStream1.Close(); MyFileStream2.Close(); } }
}
</source>
Write byte array to a file
<source lang="csharp">
using System; using System.Collections.Generic; using System.Text; using System.IO; class Program {
static void Main(string[] args) { byte[] byData; char[] charData; try { FileStream aFile = new FileStream("Temp.txt", FileMode.Create); charData = "www.nfex.ru".ToCharArray(); byData = new byte[charData.Length]; Encoder e = Encoding.UTF8.GetEncoder(); e.GetBytes(charData, 0, charData.Length, byData, 0, true); aFile.Seek(0, SeekOrigin.Begin); aFile.Write(byData, 0, byData.Length); } catch (IOException ex) { Console.WriteLine(ex.ToString()); return; } }
}
</source>