Download Source Code Sample
I've gotten a lot of questions from vb 6.0 developers transitioning to .NET concerning the basics of working with files in .NET. They come from the Scripting.FileSystemObject world. So, I've worked up this sample to help you guys get started working with files in .NET.
You'll want to take notice of the "using" clause that is wrapped around the FileStream, BinaryReader, BinaryWriter, StreamReader, and StreamWriter oriented code blocks.
The using clause forces .NET to always call the .Dispose() method on classes that implement the IDisposable interface which these do. The .Dispose() method will get called whether an error occurred or not. If you disassemble the .net framework System.IO assembly, you'll find that the .Dispose() method of these classes always calls its base class Stream .Dispose() method.
The Stream .Dispose() method always calls its .Close() method which closes any file connections it may still have. Most of the .NET classes that implement IDisposable will eventually get down to a .Close() method somewhere in the class hierarchy. However, you can't always be certain that 3rd party or open source controls/assemblies will do the same.
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using System.Text;
namespace FileSystemObject
{
class Program
{
static void Main(string[] args)
{
byte[] binary = null;
string folder = @"C:\temp";
string text = "line 1\nline 2\nline 3";
string textFileName = "test.txt";
string binaryFileName = "test.dat";
string fullFileName = "";
try
{
fullFileName = Path.Combine(folder, textFileName);
// Creating directory
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
WriteTextFile(fullFileName,text);
text = ReadTextFile(fullFileName);
Console.WriteLine(text);
// Sample to delete file
if (File.Exists(fullFileName))
{
File.Delete(fullFileName);
}
WriteTextFile(fullFileName, text);
DisplayTextFileLineByLine(fullFileName);
// Binary/Image file samples
fullFileName = Path.Combine(folder, binaryFileName);
// Convert text string to sample binary
UTF8Encoding encoding = new UTF8Encoding();
binary = encoding.GetBytes(text);
// Write the binary contents to a binary file
WriteBinaryFile(fullFileName,binary);
// Read the entire binary file into a byte[]
binary = ReadBinaryFile(fullFileName);
if (binary != null)
{
// Convert the byte[] back to a string
text = encoding.GetString(binary, 0, binary.Length);
}
Console.Write(text);
Console.WriteLine("");
DirectoryInfo directory = new DirectoryInfo(folder);
CreateFolderTree(directory,6);
DisplayFolderNames(directory);
Console.WriteLine("done");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally { Console.ReadLine(); }
}
#region Read Binary File
public static byte[] ReadBinaryFile(string fileName)
{
try
{
using (FileStream fs = new FileStream(fileName,
FileMode.Open,
FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
return br.ReadBytes((int)fs.Length);
}
}
}
catch (Exception) { throw; }
}
#endregion
#region Write Binary File
public static void WriteBinaryFile(string fileName, byte[] binary)
{
try
{
using (FileStream fs = new FileStream(fileName,FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(binary);
}
}
}
catch (Exception) { throw; }
}
#endregion
#region Write Text File
public static void WriteTextFile(string fileName,string contents)
{
try
{
using(StreamWriter sw = new StreamWriter(fileName,false))
{
sw.Write(contents);
}
}
catch (Exception) { throw; }
}
#endregion
#region Read Text File
public static string ReadTextFile(string fileName)
{
try
{
using (StreamReader sr = new StreamReader(fileName))
{
return sr.ReadToEnd();
}
}
catch (Exception) { throw; }
}
#endregion
#region Display Text File Line By Line
public static void DisplayTextFileLineByLine(string fileName)
{
try
{
using (StreamReader sr = new StreamReader(fileName))
{
while(sr.Peek()>0)
{
Console.WriteLine(sr.ReadLine());
}
}
}
catch (Exception) { throw; }
}
#endregion
#region Create Folder Tree
public static void CreateFolderTree(DirectoryInfo directory,
int numberOfSubFolders)
{
string folderName ="";
try
{
for (int i = 0; i < numberOfSubFolders; i++)
{
folderName = Path.Combine(directory.FullName, "test" + i.ToString());
if (!Directory.Exists(folderName))
{
CreateFolderTree(Directory.CreateDirectory(folderName), i-1);
}
}
}
catch (Exception) { throw; }
}
#endregion
#region Display Folder Names
public static void DisplayFolderNames(DirectoryInfo directory)
{
DirectoryInfo[] directories = null;
FileInfo[] files = null;
try
{
files = directory.GetFiles();
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
Console.WriteLine(files[i].FullName);
}
}
directories = directory.GetDirectories("*test*");
if (directories == null) { return; }
for(int i=0;i<directories.Length;i++)
{
Console.WriteLine(directories[i].FullName);
DisplayFolderNames(directories[i]);
}
}
catch (Exception) { throw; }
}
#endregion
}
} |