#region License
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.IO;
namespace Spring.Util
{
/// <summary>
/// Utility methods for IO handling
/// </summary>
internal sealed class IOUtils
{
private IOUtils()
{
throw new InvalidOperationException("instantiation not supported");
}
/// <summary>
/// Copies one stream into another.
/// (Don't forget to call <see cref="Stream.Flush"/> on the destination stream!)
/// </summary>
/// <remarks>
/// Does not close the input stream!
/// </remarks>
public static void CopyStream(Stream src, Stream dest)
{
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
while ((bytesRead = src.Read(buffer, 0, bufferSize)) > 0)
{
dest.Write(buffer, 0, bytesRead);
}
}
}
}
File Stream
Reads a stream into a byte array.
#region License
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.IO;
namespace Spring.Util
{
/// <summary>
/// Utility methods for IO handling
/// </summary>
internal sealed class IOUtils
{
private IOUtils()
{
throw new InvalidOperationException("instantiation not supported");
}
/// <summary>
/// Reads a stream into a byte array.
/// </summary>
/// <remarks>
/// Does not close the input stream!
/// </remarks>
public static byte[] ToByteArray(Stream src)
{
MemoryStream stm = new MemoryStream();
CopyStream(src, stm);
stm.Close();
return stm.ToArray();
}
/// <summary>
/// Copies one stream into another.
/// (Don't forget to call <see cref="Stream.Flush"/> on the destination stream!)
/// </summary>
/// <remarks>
/// Does not close the input stream!
/// </remarks>
public static void CopyStream(Stream src, Stream dest)
{
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
while ((bytesRead = src.Read(buffer, 0, bufferSize)) > 0)
{
dest.Write(buffer, 0, bytesRead);
}
}
}
}
Utility class that provides methods to manipulate stream of data.
#region License and Copyright
/* ————————————————————————-
* Dotnet Commons IO
*
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
*
* Free Software Foundation, Inc.,
* 59 Temple Place,
* Suite 330,
* Boston,
* MA 02111-1307
* USA
*
* ————————————————————————-
*/
#endregion
using System;
using System.IO;
using System.Text;
namespace Dotnet.Commons.IO
{
///
///
///
/// This class is ported from Jakarta Commons IO org.apache.commons.io.CopyUtils class.
///
/// This class also contains code taken from an article written by Jon Skeet. The
/// article can be found here:
/// http://www.developerfusion.co.uk/show/4696/
///
public sealed class StreamUtils
{
///
private const int DEFAULT_BUFFER_SIZE = 1024 * 4;
private StreamUtils(){}
public static void Copy(byte[] input, byte[] output, long outputOffset)
{
if (input.Length == 0) return;
for (int i=0; i /// the byte array to read from output.Write(input, 0, input.Length); /// /// the byte array to read from
/// the /// ///
///
///
public static void Copy(byte[] input, StreamWriter outputWriter, string encoding) /// /// the Input /// /// the Input if (copyFromBeginning) // set it to the beginning return bytesRead; // —————————————————————- /// /// the while (len > 0) // —————————————————————- /// /// the Input /// ///
///
/// The name of a supported character encoding. See the try // —————————————————————- /// /// the outputWriter.Flush(); // —————————————————————- /// the outWriter.Flush(); // —————————————————————- /// /// the /// /// Source while (bytesRead < len)
{
int sizeNeeded = Math.Min(buffer.Length, len - bytesRead);
int readSize = source.Read(buffer, 0, sizeNeeded);
if (readSize <= 0)
throw new IOException(String.Format("Underlying stream does not have enough data. Read {0} bytes, but {1} needed", readSize, sizeNeeded));
target.Write(buffer, 0, readSize);
bytesRead += readSize;
}
}
///
/// The stream to read data from
/// The array to read bytes into. The array /// The stream to read data from
/// byte[] byteArray = new byte[DEFAULT_BUFFER_SIZE]; /// The stream to read data from
/// The initial buffer length. If the length is < 1, // If we've reached the end of our buffer, check to see if there's // End of stream? If so, we're done // Nope. Resize the buffer, put in the byte we've just /// ///
/// /// ///
/// /// ///
///
/// if (stream == null) byte[] bytes = new byte[stream.Length]; if (stream is MemoryStream) return encoding.GetString(bytes); /// /// Source stream to read from
/// Target byte array to write to
/// offset index in the target
/// offset position in the stream
/// number of bytes to read in the stream
/// if (targetOffset + bytesToRead > target.Length) int bytesRead = 0; /// Source stream to read from
/// the starting offset position in the stream. Set to 0 if the stream is to be read from the beginning.
/// number of bytes to read
/// byte[] target = new byte[bytesToRead]; long bytesRead = 0; while (bytesRead < bytesToRead)
{ // need more data
int sizeNeeded = (int)Math.Min((long)DEFAULT_BUFFER_SIZE, bytesToRead - bytesRead);
// read either the whole buffer length or
// the remaining # of bytes: bytesToRead - sizeNeeded
int readSize = source.Read(target, 0, sizeNeeded);
if (readSize <= 0)
throw new IOException(String.Format("Underlying stream does not have enough data. Read {0} bytes, but {1} needed", readSize, sizeNeeded));
bytesRead += readSize;
}
return target;
}
///
/// the stream to read
/// the stream to write to
[Obsolete(“See StreamUtils.Copy”)] /// /// Input stream that will be used to skip the bytes
/// Number of bytes to be skipped
/// /// /// The stream in which the skips are done.
/// The number of caracters to skip.
/// /// The StringReader in which the skips are done.
/// The number of caracters to skip.
/// /// The string to be converted
/// /// /// Array to convert.
///
///
/// the Output
///
///
public static void Copy(byte[] input, Stream output)
{
if (input.Length == 0) return;
}
///
///
public static void Copy(byte[] input, StreamWriter outputWriter)
{
MemoryStream inputStream = new MemoryStream(input);
Copy(inputStream, outputWriter);
}
///
///
{
MemoryStream inputStream = new MemoryStream(input);
Copy(inputStream, outputWriter, encoding);
}
///
/// the Output
///
///
///
///
public static int Copy(Stream input, Stream output)
{
return Copy(input, output, false);
}
///
/// the Output
///
/// Set true to copy from the beginning of the input stream, eg. input.Position=0,
/// otherwise, it will start copying from whatever the current position in the input stream.
///
///
///
///
public static int Copy(Stream input, Stream output, bool copyFromBeginning)
{
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int bytesRead = 0;
int len = DEFAULT_BUFFER_SIZE;
int offset=0;
input.Seek(0, SeekOrigin.Begin);
while (len > 0)
{
len = input.Read(buffer, offset, DEFAULT_BUFFER_SIZE);
output.Write(buffer, 0, len);
bytesRead += len;
}
}
// Reader -> Writer
// —————————————————————-
///
/// the
///
///
///
///
public static int Copy(StreamReader inputStreamReader, StreamWriter outputStreamWriter)
{
char[] buffer = new char[DEFAULT_BUFFER_SIZE];
int count = 0;
int len = DEFAULT_BUFFER_SIZE;
{
len = inputStreamReader.Read(buffer, 0, DEFAULT_BUFFER_SIZE);
outputStreamWriter.Write(buffer, 0, len);
count += len;
}
return count;
}
// InputStream -> Writer
// —————————————————————-
///
/// The platform's default encoding is used for the byte-to-char conversion.
///
///
/// the
///
///
public static int Copy(Stream inputStream, StreamWriter outputStreamWriter)
{
StreamReader inputStreamReader = new StreamReader(inputStream, System.Text.Encoding.Default);
return Copy(inputStreamReader, outputStreamWriter);
}
///
///
/// IANA
/// Charset Registry and MSDN: Encoding class
/// for a list of valid encoding types.
///
public static int Copy(Stream inputStream, StreamWriter outputWriter, String encoding)
{
Encoding encode = Encoding.Default;
{
encode = Encoding.GetEncoding(encoding);
}
catch
{
encode = Encoding.Default;
}
StreamReader inputStreamReader = new StreamReader(inputStream, encode);
return Copy(inputStreamReader, outputWriter);
}
// Reader -> OutputStream
// —————————————————————-
/// Output
///
public static void Copy(StreamReader inputReader, Stream output)
{
StreamWriter outputWriter = new StreamWriter(output, System.Text.Encoding.Default);
Copy(inputReader, outputWriter);
}
// String -> OutputStream
// —————————————————————-
///
/// Output
/// flush the Output
///
///
/// the Output
///
///
public static void Copy(String input, Stream output)
{
byte[] inputByteArray = new ASCIIEncoding().GetBytes(input);
StreamWriter outWriter = new StreamWriter(output, System.Text.Encoding.Default);
Copy(inputByteArray, outWriter);
}
// String -> Writer
// —————————————————————-
///
/// the
///
///
public static void Copy(String input, StreamWriter output)
{
output.Write(input);
}
/// target
///
public static void CopyExact(Stream source, Stream target, int len)
{
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int bytesRead = 0;
/// if the stream runs out of data first, or if an IOException
/// naturally occurs.
///
/// will be completely filled from the stream, so an appropriate
/// size must be given.
public static void ReadIntoByteArray (Stream stream, byte[] byteArray)
{
int offset=0;
int remaining = byteArray.Length;
stream.Position = 0;
while (remaining > 0)
{
int read = stream.Read(byteArray, offset, remaining);
if (read <= 0)
throw new EndOfStreamException
(String.Format("End of stream reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}
///
/// data is returned as a byte array.
///
///
/// (for instance a network stream) and just want to read the whole lot into a buffer.
///
/// This method of reading the stream is not terribly efficient.
///
public static byte[] GetBytes(Stream stream)
{
if (stream is MemoryStream)
return ((MemoryStream)stream).ToArray();
using (MemoryStream ms = new MemoryStream())
{
stream.Position = 0;
while (true)
{
int readLen = stream.Read (byteArray, 0, byteArray.Length);
if (readLen <= 0)
return ms.ToArray();
ms.Write (byteArray, 0, readLen);
}
}
}
///
/// data is returned as a byte array.
///
/// then the default value of
///
///
///
public static byte[] GetBytes (Stream stream, long initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
initialLength = Int16.MaxValue;
byte[] buffer = new byte[initialLength];
int read=0;
int chunk;
while ( (chunk = stream.Read(buffer, read, buffer.Length-read)) > 0)
{
read += chunk;
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte==-1)
{
return buffer;
}
// read, and continue
byte[] newBuffer = new byte[buffer.Length*2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read]=(byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
///
public static string GetAsciiString(Stream stream)
{
ASCIIEncoding encoding = new ASCIIEncoding();
return GetString(stream, encoding);
}
///
public static string GetString(Stream stream)
{
UTF8Encoding encoding = new UTF8Encoding();
return GetString(stream, encoding);
}
/// the encoding provided.
///
public static string GetString(Stream stream, Encoding encoding)
{
return string.Empty;
bytes = ((MemoryStream)stream).GetBuffer();
else
ReadIntoByteArray(stream, bytes);
}
/// specific byte array in a specific start index position. The byte
/// array must have the necessary size to read the portion of the stream required.
///
/// the required number of bytes read from the stream.
public static void ReadExact(Stream source,
byte[] target,
int sourceOffset,
int targetOffset,
int bytesToRead)
{
throw new ArgumentException(“target array to small”);
source.Seek(sourceOffset, SeekOrigin.Begin);
while (bytesRead < bytesToRead)
{ // need more data
int sizeNeeded = Math.Min(DEFAULT_BUFFER_SIZE, bytesToRead - bytesRead);
// read either the whole buffer length or
// the remaining # of bytes: bytesToRead - sizeNeeded
int readSize = source.Read(target, (targetOffset + bytesRead), sizeNeeded);
if (readSize <= 0)
throw new IOException(String.Format("Underlying stream does not have enough data. Read {0} bytes, but {1} needed", readSize, sizeNeeded));
bytesRead += readSize;
}
}
///
///
public static byte[] ReadPartial(Stream source,
long sourceOffset,
long bytesToRead)
{
long sizeDiff = source.Length – sourceOffset;
if (bytesToRead > sizeDiff)
throw new ArgumentException(“Bytes required exceeds what is available in stream”);
source.Seek(sourceOffset, SeekOrigin.Begin);
///
public static void ReadWriteStream(Stream readStream, Stream writeStream)
{
Byte[] buffer = new Byte[DEFAULT_BUFFER_SIZE];
int bytesRead = readStream.Read(buffer, 0, DEFAULT_BUFFER_SIZE);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, DEFAULT_BUFFER_SIZE);
}
readStream.Close();
writeStream.Close();
}
///
public static int Skip(Stream stream, int skipBytes)
{
long oldPosition = stream.Position;
long result = stream.Seek(skipBytes, SeekOrigin.Current) – oldPosition;
return (int)result;
}
///
public static long Skip(StreamReader stream, long number)
{
long skippedBytes = 0;
for (long index = 0; index < number; index++)
{
stream.Read();
skippedBytes++;
}
return skippedBytes;
}
///
///
public static long Skip(StringReader strReader, long number)
{
long skippedBytes = 0;
for (long index = 0; index < number; index++)
{
strReader.Read();
skippedBytes++;
}
return skippedBytes;
}
///
///
public static byte[] ToByteArray(String sourceString)
{
return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString);
}
///
public static byte[] ToByteArray(Object[] tempObjectArray)
{
byte[] byteArray = null;
if (tempObjectArray != null)
{
byteArray = new byte[tempObjectArray.Length];
for (int index = 0; index < tempObjectArray.Length; index++)
byteArray[index] = (byte)tempObjectArray[index];
}
return byteArray;
}
}
}
[/csharp]
Using StreamWriter 3
/*
* 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 UsingStreamWriter {
static void Main(string[] args)
{
//StreamWriter can only be use to write to files or other streams
StreamWriter MyStreamWriter = new StreamWriter(@”c:ProjectsTesting.txt”);
//You can also use FileStream with StreamWriter to provide a greater degree of control
//in how you open the file
FileStream MyFileStream = new FileStream(@”c:ProjectsTesting.txt”, FileMode.CreateNew, FileAccess.Write, FileShare.None);
StreamWriter MyStreamWriter2 = new StreamWriter(MyFileStream);
MyFileStream.Close();
MyStreamWriter2.Close();
//You can write sequentially to a file using this technique
FileInfo MyFile = new FileInfo(@”c:ProjectsTesting.txt”);
StreamWriter MyStreamWriter3 = MyFile.CreateText();
MyStreamWriter3.Close();
//There are four overloaded ways to use StreamWriter.Write()
//Writes a stream to a file
string MyString = “Hello World”;
MyStreamWriter.Write(MyString);
//Writes single characters to a stream
char MyChar = 'A';
MyStreamWriter.Write(MyChar);
//Writes an Array of characters
char[] MyCharArray = new char[100];
for (int i = 0; i < 99; i++) { MyCharArray[i] = (char)i; } MyStreamWriter.Write(MyCharArray); //or you can write a portion of an array MyStreamWriter.Write(MyCharArray, 25, 30); MyStreamWriter.Close(); } } } [/csharp]
Try and catch exceptions for StreamWriter
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
*/
using System;
using System.IO;
namespace Client.Chapter_9___Exceptions_and_AppDomains
{
public class MyMainClassChapter_9___Exceptions_and_AppDomains
{
delegate int MyDelegate(string s);
static void Main(string[] args)
{
StreamWriter MyStream = null;
string MyString = "Hello World";
try
{
MyStream = File.CreateText("MyFile.txt");
MyStream.Write(MyString);
}
catch (IOException e)
{
Console.WriteLine(e);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (MyStream != null)
MyStream.Close();
}
}
}
public class MyFile
{
public StreamWriter WriteText(string s)
{
if (!Valid(s))
throw new IOException("Can't Write String");
else
return new StreamWriter("c: est.txt");
}
public bool Valid(string s)
{
return false;
}
}
}
A help program that uses a disk file to store help information
/*
C# A Beginner's Guide
By Schildt
Publisher: Osborne McGraw-Hill
ISBN: 0072133295
*/
/*
Project 11-2
A help program that uses a disk file
to store help information.
*/
using System;
using System.IO;
/* The Help class opens a help file,
searches for a topic, and then displays
the information associated with that topic. */
class Help {
string helpfile; // name of help file
public Help(string fname) {
helpfile = fname;
}
// Display help on a topic.
public bool helpon(string what) {
StreamReader helpRdr;
int ch;
string topic, info;
try {
helpRdr = new StreamReader(helpfile);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message);
return false;
}
try {
do {
// read characters until a # is found
ch = helpRdr.Read();
// now, see if topics match
if(ch == '#') {
topic = helpRdr.ReadLine();
if(what == topic) { // found topic
do {
info = helpRdr.ReadLine();
if(info != null) Console.WriteLine(info);
} while((info != null) && (info != ""));
helpRdr.Close();
return true;
}
}
} while(ch != -1);
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
}
helpRdr.Close();
return false; // topic not found
}
// Get a Help topic.
public string getSelection() {
string topic = "";
Console.Write("Enter topic: ");
try {
topic = Console.ReadLine();
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
return "";
}
return topic;
}
}
// Demonstrate the file-based Help system.
public class FileHelp {
public static void Main() {
Help hlpobj = new Help("helpfile.txt");
string topic;
Console.WriteLine("Try the help system. " +
"Enter 'stop' to end.");
do {
topic = hlpobj.getSelection();
if(!hlpobj.helpon(topic))
Console.WriteLine("Topic not found.
");
} while(topic != "stop");
}
}
/*
#if
if(condition) statement;
else statement;
#switch
switch(expression) {
case constant:
statement sequence
break;
// ...
}
#for
for(init; condition; iteration) statement;
#while
while(condition) statement;
#do
do {
statement;
} while (condition);
#break
break; or break label;
#continue
continue; or continue label;
#goto
goto label;
*/
Open a file using StreamWriter
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Open a file using StreamWriter.
using System;
using System.IO;
public class KtoD1 {
public static void Main() {
string str;
StreamWriter fstr_out;
// Open the file directly using StreamWriter.
try {
fstr_out = new StreamWriter("test.txt");
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "Cannot open file.");
return ;
}
Console.WriteLine("Enter text ('stop' to quit).");
do {
Console.Write(": ");
str = Console.ReadLine();
if(str != "stop") {
str = str + "
"; // add newline
try {
fstr_out.Write(str);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "File Error");
return ;
}
}
} while(str != "stop");
fstr_out.Close();
}
}