MorkaLork Development

Interesting stuff I've picked up over the years...

System.IO examples

2009-04-17 07:31:18 | 243 views | filestream stream streamreader streamwriter file file.delete file.exists system.io

General examples



Here are a couple of examples of how to use the System.IO namespace



public class program
{
public static void Main()
{
//The paths to our files
string bytePath = @"C:UsersmaffeluDocumentsSharpFilesFile1.txt";
string stringPath = @"C:UsersmaffeluDocumentsSharpFilesFile2.txt";

//A header :)
Console.WriteLine("Filestream:");

#region filestreamCreate
using(FileStream filestream = new FileStream(bytePath, FileMode.Create))
{
//Create an array of bytes
byte[] bytesOut = new byte[]{66, 65, 64, 63};

//Write the bytes to file
filestream.Write(bytesOut, 0, bytesOut.Length);

Console.WriteLine("Bytes written to {0}", filestream.Name);
}
#endregion

#region filereadRead
using(FileStream filestream = new FileStream(bytePath, FileMode.Open, FileAccess.Read))
{
//Create an array consistent to the length of the bytes in the file
byte[] bytesInFile = new byte[filestream.Length];
int bytesToRead = (int)filestream.Length;
int bytesRead = 0;

//This reads until there are no bytes left to read
while (bytesToRead > 0) {

//If the file has reached the end, stop
int i = filestream.Read(bytesInFile, bytesRead, bytesToRead);
if (i == 0) {
break;
}

bytesRead += i;
bytesToRead -= i;
}

//Output the bytes
Console.Write("The following bytes where found in the file: ");
foreach(byte b in bytesInFile)
{
Console.Write(b + " ");
}

//Output the bytes in string format
string bytesToString = System.Text.ASCIIEncoding.ASCII.GetString(bytesInFile);
Console.WriteLine("
The bytes in string format: {0}", bytesToString);
}

#endregion

//A header :)
Console.WriteLine("");
Console.WriteLine("StreamReader/StreamWriter:");

#region StreamWriter
//Write the file
using(StreamWriter streamwriter = new StreamWriter(stringPath))
{
//Write three lines to file
streamwriter.WriteLine("Hello word?");
streamwriter.WriteLine("Hello worm?");
streamwriter.WriteLine("Hello world!");

Console.WriteLine("Strings written to {0}", stringPath);
}
#endregion

#region StreamReader
using(StreamReader streamreader = new StreamReader(stringPath))
{
//Create a line to handle the reading
string lines;
Console.WriteLine("Reading {0}", stringPath);

//We read each line to our string variable lines
while ((lines = streamreader.ReadLine()) != null) {
Console.WriteLine(lines);
}
}
#endregion

//A header :)
Console.WriteLine("");
Console.WriteLine("File()");

#region File
//If file exists, exterminate it!
if (File.Exists(bytePath)) {
Console.WriteLine("File found: {0}", bytePath);
File.Delete(bytePath);
Console.WriteLine("File deleted!");
}

//Now, create a real, fine file
using(FileStream filestream = File.Create(bytePath))
{
byte[] b = new byte[]{66, 65, 64, 63};
filestream.Write(b, 0, b.Length);
Console.WriteLine("File {0} created!", bytePath);
}

//Read all the bytes in the file to array
try {
//Use the ReadAllBytes to read all the bytes from the file to a byte array
byte[] bytes = File.ReadAllBytes(bytePath);
Console.Write("The following bytes where found: ");

//Loop through the byte array
foreach(byte b in bytes)
{
Console.Write("{0} ", b);
}

string s = System.Text.ASCIIEncoding.ASCII.GetString(bytes);
Console.WriteLine("
The bytes in string format: {0}", s);
} catch (FileNotFoundException ex) {
Console.WriteLine("Error: {0}", ex.ToString());
}

#endregion


//The header
Console.WriteLine("");
Console.WriteLine("Directory");

#region Directory
//List all files in the directory
string[] fileArray = Directory.GetFiles(@"C:UsersmaffeluDocumentsSharpFiles");
foreach(string s in fileArray)
{
Console.WriteLine(s);
}
#endregion


//The header :)
Console.WriteLine("");
Console.WriteLine("Path");

#region Path
/*The following are the paths we have:
*
*bytePath = @"C:UsersmaffeluDocumentsSharpFilesFile1.txt";
*stringPath = @"C:UsersmaffeluDocumentsSharpFilesFile2.txt";
*tempPath = @"File"; <--New one, in the root of our project
*
*/
string tempPath = @"File";
File.Create(tempPath);

//Check if the file has an extension
switch (Path.HasExtension(stringPath)) {
case true:
Console.WriteLine(""{0}" has an extension", Path.GetFileName(stringPath));
break;
case false:
Console.WriteLine(""{0}" has no extension", Path.GetFileName(stringPath));
break;
}
switch (Path.HasExtension(tempPath)) {
case true:
Console.WriteLine(""{0}" has an extension", Path.GetFileName(tempPath));
break;
case false:
Console.WriteLine(""{0}" has no extension", Path.GetFileName(tempPath));
break;
}

//Get the full path of our file File :)
Console.WriteLine("The full path of "{0}" is {1}", tempPath, Path.GetFullPath(tempPath));
#endregion


//The header :)
Console.WriteLine("");
Console.WriteLine("Cleaning up...");

#region CleanUp
//Here we delete the files we created in order to restore peace on the harddrive...
try {
File.Delete(bytePath);
File.Delete(stringPath);
Console.WriteLine("The following files have been deleted:
{0}
{1}", bytePath, stringPath);
} catch (FileNotFoundException ex) {
Console.WriteLine("Error: {0}", ex.ToString());
}
#endregion

Console.Write("
Press any key to exit...");
Console.Read();
}
}


This will create the following output:
imagehttp://admin.morkalork.com/uploads/images/IO.png


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.