Skip to main content

Reading and Writing Files with .Net



Understanding Streams:
Sequential and random access streams.

All stream classes inherit from Stream class, these classes include: FileStream (System.IO), MemoryStream (System.IO), CryptoStream(System.Security), NetworkStream(System.Net), GZipStream(System.Compression).

File class is an important class used to open file for reading/writing, Exist, Delete, Move and etc…
Create/open Methods of File will return FileStream Object.

For Sequential reading and writing some methods also return StreamReader and StreamWriter and they encapsulate FileSteam object.
Few simple operations are identical to FileInfo object.

MemoryStream is a specialized class provided to manage data in memory stream to gain some optimization.

How to read from a File:
FileStream theFile = File.Open(@“C:\boot.ini”, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(thefile);
Console.Write(sr.ReadToEnd());
Sr.Close();
theFile.Close();

OR

StreamReader sr = File.OpenText(@“C:\boot.ini”);
Console.Write(sr.ReadToEnd());
Sr.Close();

OR

Console.Write(File.ReadAllText(@“C:\boot.ini”));

OR

StreamReader sr = File.OpenText(@“C:\boot.ini”);
While(!sr.EndOfStream)
{
                Console.WriteLine(sr.readLine());
}
Sr.Close();


StreamWriter:
Write
WriteLine
Overloaded. Writes to the stream.
Writes a complete line.

StreamWriter Properties:
Name
Description
AutoFlush
Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to StreamWriter.Write.
BaseStream
Gets the underlying stream that interfaces with a backing store.
Encoding
Gets the Encoding in which the output is written. (Overrides .Encoding.)
FormatProvider
Gets an object that controls formatting. (Inherited from TextWriter.)
NewLine
Gets or sets the line terminator string used by the current TextWriter. (Inherited from TextWriter.)


How to Write to a File:

FileStream theFile = new FileStream(@“C:\boot.ini”);
StreamWriter sw = new StreamWriter(theFile);
Sw.WriteLine(“testing testing ……”);
Sw.Close();
theFile.Close();

OR

StreamWriter sw = File.CreateText(@“C:\boot.ini”);
Sw.WriteLine(“testing testing ……”);
Sw.Close();

OR

File.WriteAllText(@“C:\boot.ini”, “testing testing ….. ”);

OR

FileStream theFile = File.OpenWrite(@“C:\boot.ini”);

OR

theFile = File.Open(@“C:\boot.ini”, FileMode.OpenOrCreate, FileAccess.Write);

Understanding Reader and writers
StringReader and StringWriter classes can be used to manipulate in memory strings.

BinaryReader and BinaryWriter can be used to read/write from/to manipulate binary data.

FileStream theFile = new FileStream(@“C:\boot.ini”);
BinarWriter bw = new BinaryWriter(theFile);

Bw.Writer(10);
Bw.Writer(60);
Bw.Writer(new byte[]{10,20});

Bw .close();
BinarReader br=new BinaryReader(thefile);
Br.ReadInt(); Br.ReadInt(); Br.ReadBytes(2);

Br.Close(); theFile.Close();

MemoryStream Class
MemoryStreams behaves like normal streams, but it avoids making a physical resource remained open for a longer time. MemoryStream provides a method to write data directly to another stream. Like:

MemoryStream.WriteTo(theFile);

BufferedStream class
                                BufferedStream sits in-between FileStream and StreamReader/Writer class. And it improves performance.

FileStream theFile = new FileStream(@“C:\boot.ini”);
BufferedStream bs = new BufferedStream(theFile);
StreamWriter sw = new StreamWriter(bs);
Sw.WriteLine(“testing testing ……”);
Sw.Close();
theFile.Close();


Stream Class:
Stream Properties:
Name
Description
CanRead
When overridden in a derived class, gets a value indicating whether the current stream supports reading.
CanSeek
When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
CanTimeout
Gets a value that determines whether the current stream can time out.
CanWrite
When overridden in a derived class, gets a value indicating whether the current stream supports writing.
Length
When overridden in a derived class, gets the length in bytes of the stream.
Position
When overridden in a derived class, gets or sets the position within the current stream.
ReadTimeout
Gets or sets a value that determines how long the stream will attempt to read before timing out.
WriteTimeout
Gets or sets a value that determines how long the stream will attempt to write before timing out.

Public Properties:
Name
Description
BeginRead
Begins an asynchronous read operation.
BeginWrite
Begins an asynchronous write operation.
Close
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
EndRead
Waits for the pending asynchronous read to complete.
EndWrite
Ends an asynchronous write operation.
Flush
When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
Read
When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
ReadByte
Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
Seek
When overridden in a derived class, sets the position within the current stream.
SetLength
When overridden in a derived class, sets the length of the current stream.
Synchronized
Creates a thread-safe (synchronized) wrapper around the specified Stream object.
Write
When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
WriteByte
Writes a byte to the current position in the stream and advances the position within the stream by one byte.


File Classes static methods:
Name
Description
AppendAllText
Overloaded. Appends the specified string to the file, creating the file if it does not already exist.
AppendText
Creates a StreamWriter that appends UTF-8 encoded text to an existing file.
Copy
Overloaded. Copies an existing file to a new file.
Create
Overloaded. Creates a file in the specified path.
CreateText
Creates or opens a file for writing UTF-8 encoded text.
Decrypt
Decrypts a file that was encrypted by the current account using the Encrypt(String) method.
Delete
Deletes the specified file. An exception is not thrown if the specified file does not exist.
Encrypt
Encrypts a file so that only the account used to encrypt the file can decrypt it.
Exists
Determines whether the specified file exists.
GetAccessControl
Overloaded. Gets a FileSecurity object that encapsulates the access control list (ACL) entries for a specified file.
GetAttributes
Gets the FileAttributes of the file on the path.
GetCreationTime
Returns the creation date and time of the specified file or directory.
GetCreationTimeUtc
Returns the creation date and time, in coordinated universal time (UTC), of the specified file or directory.
GetLastAccessTime
Returns the date and time the specified file or directory was last accessed.
GetLastAccessTimeUtc
Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
GetLastWriteTime
Returns the date and time the specified file or directory was last written to.
GetLastWriteTimeUtc
Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.
Move
Moves a specified file to a new location, providing the option to specify a new file name.
Open
Overloaded. Opens a FileStream on the specified path.
OpenRead
Opens an existing file for reading.
OpenText
Opens an existing UTF-8 encoded text file for reading.
OpenWrite
Opens an existing file for writing.
ReadAllBytes
Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
ReadAllLines
Overloaded. Opens a text file, reads all lines of the file into a string array, and then closes the file.
ReadAllText
Overloaded. Opens a text file, reads all lines of the file into a string, and then closes the file.
Replace
Overloaded. Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.
SetAccessControl
Applies access control list (ACL) entries described by a FileSecurity object to the specified file.
SetAttributes
Sets the specified FileAttributes of the file on the specified path.
SetCreationTime
Sets the date and time the file was created.
SetCreationTimeUtc
Sets the date and time, in coordinated universal time (UTC), that the file was created.
SetLastAccessTime
Sets the date and time the specified file was last accessed.
SetLastAccessTimeUtc
Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.
SetLastWriteTime
Sets the date and time that the specified file was last written to.
SetLastWriteTimeUtc
Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.
WriteAllBytes
Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
WriteAllLines
Overloaded. Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
WriteAllText
Overloaded. Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

Directoy Static Methods:

Name
Description
CreateDirectory
Overloaded. Creates all the directories in a specified path.
Delete
Overloaded. Deletes a specified directory.
Exists
Determines whether the given path refers to an existing directory on disk.
GetAccessControl
Overloaded. Returns the Windows access control list (ACL) for a directory.
GetCreationTime
Gets the creation date and time of a directory.
GetCreationTimeUtc
Gets the creation date and time, in Coordinated Universal Time (UTC) format, of a directory.
GetCurrentDirectory
Gets the current working directory of the application.
GetDirectories
Overloaded. Gets the names of subdirectories in a specified directory.
GetDirectoryRoot
Returns the volume information, root information, or both for the specified path.
GetFiles
Overloaded. Returns the names of files in a specified directory.
GetFileSystemEntries
Overloaded. Returns the names of all files and subdirectories in a specified directory.
GetLastAccessTime
Returns the date and time the specified file or directory was last accessed.
GetLastAccessTimeUtc
Returns the date and time, in Coordinated Universal Time (UTC) format, that the specified file or directory was last accessed.
GetLastWriteTime
Returns the date and time the specified file or directory was last written to.
GetLastWriteTimeUtc
Returns the date and time, in Coordinated Universal Time (UTC) format, that the specified file or directory was last written to.
GetLogicalDrives
Retrieves the names of the logical drives on this computer in the form "<drive letter>:\".
GetParent
Retrieves the parent directory of the specified path, including both absolute and relative paths.
Move
Moves a file or a directory and its contents to a new location.
SetAccessControl
Applies access control list (ACL) entries described by a DirectorySecurity object to the specified directory.
SetCreationTime
Sets the creation date and time for the specified file or directory.
SetCreationTimeUtc
Sets the creation date and time, in Coordinated Universal Time (UTC) format, for the specified file or directory.
SetCurrentDirectory
Sets the application's current working directory to the specified directory.
SetLastAccessTime
Sets the date and time the specified file or directory was last accessed.
SetLastAccessTimeUtc
Sets the date and time, in Coordinated Universal Time (UTC) format, that the specified file or directory was last accessed.
SetLastWriteTime
Sets the date and time a directory was last written to.
SetLastWriteTimeUtc
Sets the date and time, in Coordinated Universal Time (UTC) format, that a directory was last written to.

File Class:

FileAccess Enumeration:
Class
Description
Read
Read access to the file. Data can be read from the file. Combine with Write for read/write access.
ReadWrite
Read and write access to the file. Data can be written to and read from the file.
Write
Write access to the file. Data can be written to the file. Combine with Read for read/write access.

FileMode Enumeration:
Class
Description
Append
Opens the file if it exists and seeks to the end of the file, or creates a new file. FileMode.Append can only be used in conjunction with FileAccess.Write. Attempting to seek to a position before the end of the file will throw an IOException and any attempt to read fails and throws an NotSupportedException.
Create
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write. System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate.
CreateNew
Specifies that the operating system should create a new file. This requires FileIOPermissionAccess.Write. If the file already exists, an IOException is thrown.
Open
Specifies that the operating system should open an existing file. The ability to open the file is dependent on the the value specified by FileAccess. A System.IO.FileNotFoundException is thrown if the file does not exist.
OpenOrCreate
Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess.Read, FileIOPermissionAccess.Read is required. If the file access is FileAccess.Write then FileIOPermissionAccess.Write is required. If the file is opened with FileAccess.ReadWrite, both FileIOPermissionAccess.Read and FileIOPermissionAccess.Write are required. If the file access is FileAccess.Append, then FileIOPermissionAccess.Append is required.
Truncate
Specifies that the operating system should open an existing file. Once opened, the file should be truncated so that its size is zero bytes. This requires FileIOPermissionAccess.Write. Attempts to read from a file opened with Truncate cause an exception.

FileStream Properties:
Name
Description
CanRead
Gets a value indicating whether the current stream supports reading. (Overrides .CanRead.)
CanSeek
Gets a value indicating whether the current stream supports seeking. (Overrides .CanSeek.)
CanTimeout
Gets a value that determines whether the current stream can time out. (Inherited from Stream.)
CanWrite
Gets a value indicating whether the current stream supports writing. (Overrides .CanWrite.)
Handle
Gets the operating system file handle for the file that the current FileStream object encapsulates.
IsAsync
Gets a value indicating whether the FileStream was opened asynchronously or synchronously.
Length
Gets the length in bytes of the stream. (Overrides .Length.)
Name
Gets the name of the FileStream that was passed to the constructor.
Position
Gets or sets the current position of this stream. (Overrides .Position.)
ReadTimeout
Gets or sets a value that determines how long the stream will attempt to read before timing out. (Inherited from Stream.)
SafeFileHandle
Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.
WriteTimeout
Gets or sets a value that determines how long the stream will attempt to write before timing out. (Inherited from Stream.)

FileStream Methods:
Name
Description
BeginRead
Begins an asynchronous read. (Overrides .BeginRead(Byte[](), Int32, Int32, AsyncCallback, Object).)
BeginRead
Begins an asynchronous read operation. (Inherited from Stream.)
BeginWrite
Begins an asynchronous write. (Overrides .BeginWrite(Byte[](), Int32, Int32, AsyncCallback, Object).)
BeginWrite
Begins an asynchronous write operation. (Inherited from Stream.)
Close
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. (Inherited from Stream.)
Close
(Overrides .Close().)
EndRead
Waits for the pending asynchronous read to complete. (Overrides .EndRead(IAsyncResult).)
EndRead
Waits for the pending asynchronous read to complete. (Inherited from Stream.)
EndWrite
Ends an asynchronous write, blocking until the I/O operation has completed. (Overrides .EndWrite(IAsyncResult).)
EndWrite
Ends an asynchronous write operation. (Inherited from Stream.)
Flush
Clears all buffers for this stream and causes any buffered data to be written to the file system. (Overrides .Flush().)
GetAccessControl
Gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object.
GetHashCode
Serves as a hash function for a particular type. (Inherited from Object.)
GetType
Gets the Type of the current instance. (Inherited from Object.)
Lock
Prevents other processes from changing the FileStream while permitting read access.
Read
Reads a block of bytes from the stream and writes the data in a given buffer. (Overrides .Read(Byte[](), Int32, Int32).)
ReadByte
Reads a byte from the file and advances the read position one byte. (Overrides .ReadByte().)
Seek
Sets the current position of this stream to the given value. (Overrides .Seek(Int64, SeekOrigin).)
SetAccessControl
Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object.
SetLength
Sets the length of this stream to the given value. (Overrides .SetLength(Int64).)
ToString
Returns a String that represents the current Object. (Inherited from Object.)
Unlock
Allows access by other processes to all or part of a file that was previously locked.
Write
Writes a block of bytes to this stream using data from a buffer. (Overrides .Write(Byte[](), Int32, Int32).)
WriteByte
Writes a byte to the current position in the file stream. (Overrides .WriteByte(Byte).)

StreamReader inherits from Stream class thus it inherits a lot of functionality from Stream base class. Readers are intended to read from streams as strings.

StreamReader Properties:
Name
Description
BaseStream
Returns the underlying stream.
CurrentEncoding
Gets the current character encoding that the current StreamReader object is using.
EndOfStream
Gets a value that indicates whether the current stream position is at the end of the stream.

StreamReader Methods:

Peek
Returns the next available character but does not consume it. (Overrides .Peek().)
Read
Overloaded. Reads the next character or next set of characters from the input stream.
ReadBlock
Reads a maximum of count characters from the current stream, and writes the data to buffer, beginning at index. (Inherited from TextReader.)
ReadLine
Reads a line of characters from the current stream and returns the data as a string. (Overrides .ReadLine().)
ReadToEnd
Reads the stream from the current position to the end of the stream. (Overrides .ReadToEnd().)

Comments

Popular posts from this blog

Culture Information and Localization in .NET

Namespace: System.Globalization CultureInfo Class:                 It provides information like the Format of numbers and dates, Culture’s Calendar, Culture’s language and sublanguage (if applicable), Country and region of the culture. The Basic use of CultureInfo class is shown here: • How string Comparisons are performed • How Number Comparison & Formats are performed • Date Comparison and Formats. • How resources are retrieved and used. Cultures are grouped into three categories: Invariant Culture : It’s Culture Insensitive. It can be used to build some trial application. It can be also used to build an application with hard-coded expiry date that ignores cultures. But using it for every comparison will be incorrect and inappropriate. Neutral Culture : English(en), Frensh(fr), and Spanish(sp). A neutral culture is related to language but it’s not related to specific regi...

Concept of App Domain in .Net

Creating Application Domains: Application domain is just like process, provides separate memory space, and isolates from other code. But it’s quite light weight. It also provides the following advantages: 1-       Reliability : If a domain crashes, it can be unloaded. Hence doesn’t affect the other assemblies. 2-       Efficiency : Loading all assemblies in one domain can be cumbersome and can make the process heavy but Appdomains are efficient in this manner. Important properties of AppDomain: ApplicationIdentity , ApplicationTrust , BaseDirectory , CurrentDomain , DomainManager , DomainDirectory , Evidence , FriendlyName , ID , RelativeSearchPath , SetupInformation , ShadowCopyFiles . Important methods of AppDomain: ApplyPolicy , CreateCOMInstanceFrom , CreateDomain , CreateInstance (Assembly). To create an AppDomain: AppDomain adomain = AppDomain.CreateDomain(“D”); To execute an assembly:...

Asynchronous Execution in ASP.NET

Asynchronous Execution: Two ways either implement IHTTPAsyncHandler interface or in ASP.NET 2.0 set <%@ Page Async=”true” %>. The second option implements IHTTPAsyncHandler interface automatically for the page when parsed or compiled. AddOnPreRenderCompleteAsync ( new BeginEventHandler(BeginTask), new EndEventHandler(EndTask)); AddOnPreRenderCompleteAsync() shoud be called in Page_load. The BeginEventHandler and EndEventHandler are delegates defined as follows: IAsyncResult BeginEventHandler( object sender, EventArgs e, AsyncCallback cb, object state) void EndEventHandler( IAsyncResult ar) AsyncProcess starts and completes between PreRender and PreRenderComplete. Other way to perform Async Task is using AsyncPageTask structure. It also allows multiple tasks to execute simultaneously. void Page_Load (object sender, EventArgs e) { PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginTask), new EndEventH...