How to Read and Write Files with Streams in ASP.NET?

File creation and processing is very common in most of the applications. This article will give you basic idea on how to read and write files in ASP.NET with the help of streams.

About File Streams: What are streams? Streams are nothing but sequence of bytes. The content in your file is represented as ordered byes. Here is an example for using file streams to read and write bytes:

FileStream tempFileStream = new FileStream(@”c:\tempFolder\tempFile.txt”, FileMode.Create);
tempFileStream.Write(bytes);

You can read these bytes as follows:
FileStream tempFileStream = new FileStream(@”c:\tempFolder\tempFile.txt”, FileMode.Open);
int fileLength = tempFileStream.Length;
byte[] fileContent = new byte[fileLength];
for(int index=0; index< fileLength; index++){
fileContent[index] = tempFileStream.ReadByte();
}

File is opened in the mode specified in FileMode. Here you have seen Create and Open values of FileMode. Other acceptable values are Append, CreateNew, OpenOrCreate and Truncate. The example above deals with bytes and byte arrays which may not be really useful for you. For your convenience, .NET provides few other classes like StreamWriter, StreamReader, BinaryReader, BinaryWriter which are discussed in detail in this article.

Reading and Writing Text Files: To read and write a text file, .NET provides StreamWriter and StreamReader classes that are available in System.IO.namespace. Here is an example to write contents into a text file:

FileStream tempFileStream = null;
StreamWriter tempStreamWriter = null;
try{
tempFileStream = = new FileStream(@”c:\tempFolder\tempFile.txt”, FileMode.Create);
tempStreamWriter = new StreamWriter(tempFileStream);
tempStreamWriter.WriteLine(“Sample text written into the file”);
tempStreamWriter.WriteLine(500000);
tempStreamWriter.WriteLine(“The above line in the file contains a number”);
}
finally{
If (tempStreamWriter != null) {
tempStreamWriter.Flush();
tempStreamWriter.Close();
}
If (tempFileStream != null) {
tempFileSteam.close();
}
}

You can create the StreamWriter in two ways: one is using “new” as mentioned above. The other alternative is to use the static methods that are available in classes named File and FileInfo. One such usage is given below:

tempStreamWriter = File.CreateText(@”c:\tempFolder\tempFile.txt”);

Now the following example will let you know how to read the file that is written above:

StreamReader tempStreamReader = null;
try{
tempStreamReader = File.OpenText(@”c:\tempFolder\tempFile.txt”);
string line1 = tempStreamReader.ReadLine();
string line2 = tempStreamReader.ReadLine();
int intForLine2 = Convert.ToInt32(line2);
string line3 = tempStreamReader.ReadLine();
}
finally{
If (tempStreamReader!= null) {
tempStreamReader.Close();
}
}

Instead of reading each line and storing in a different variable if you want to store each line as an array element, you can easily do it by having tempStreamReader.ReadLine() inside the loop until tempStreamReader.ReadLine() returns null. If it returns null, then it means that end of file is reached. Instead of ReadLine() method, you can use ReadToEnd() method if you want the entire file content as one string. Other relevant methods that are available for reading are: Read(), ReadAllText(), ReadAllBytes().

From the above examples it is evident that the contents are written into the text file as strings. If you want to parse it to a different data type when you read, then you have to do it manually.

Reading and Writing Binary Files: Using binary files will save more space but the concern is that when you open and read the file, you cannot understand the content that exists in it. .NET provides specific classes called BinaryWriter and BinaryReader to handle Binary Files. Here is an example to write contents into a binary file.

BinaryWriter tempBinaryWriter = null;
try{
tempFileStream = = new FileStream(@”c:\tempFolder\tempBinFile.bin”, FileMode.Create);
tempBinaryWriter = new BinaryWriter(tempFileStream);
string sampleText = “Sample text written into the file”;
int sampleInteger = 500000;
tempBinaryWriter.Write (sampleText);
tempBinaryWriter.Write (sampleInteger);
}
finally{
If (tempBinaryWriter!= null) {
tempBinaryWriter.Flush();
tempBinaryWriter.Close();
}
If (tempFileStream != null) {
tempFileSteam.close();
}
}

You can also use File.OpenWrite method to create a BinaryWriter as below:
tempBinaryWriter = new BinaryWriter(File.OpenWrite(@”c:\tempFolder\ tempBinFile.bin”));

Writing data into binary file is very similar to writing data into text file. But reading data has a difference. When you read an integer value from a text file, you have to read it as a string and manually parse it to integer. But here you can directly use ReadInt32() method to retrieve an integer from the file. You can read the file content that is written above as follows:

BinaryReader tempBinaryReader = null;
try{
tempBinaryReader = new BinaryReader(File.OpenRead(@”c:\tempFolder\ tempBinFile.bin”));
string line1 = tempBinaryReader.ReadString();
int line2 = tempBinaryReader.ReadInt32();
}
finally{
If (tempBinaryReader!= null) {
tempBinaryReader.Close();
}
}

Apart from reading and writing files, you can perform many other activities like renaming, uploading, copying, deleting, changing extension of files. .NET also supports features like compression and serialization.

| Understanding ASP.NET Page Lifecycle | Exploring Different Stages of Memory Management in .NET | How to Implement Forms Authentication Provider in .NET | How to Implement Toolbox Support in .NET? | Additional Ways of Ensuring Security in .NET | Memory Lifecycle in .NET – An Overview | Few Best Coding Practices for ASP .NET | Handling Session Efficiently Using SQLSERVER State Management in .NET |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.