File Manipulation in C#
A couple of the methods I have used most in the following code segment return a List object, or an ArrayList of text found inside a file to inspect.
Other methods that I've used a lot edit an existing file from a specific line number, or retrieve the full text from a specific file.
I've overloaded the AddToFile() method to allow varying ways to edit a file. Let me know if you extend this tool; I like collaboration.
-aendenne
/*
* Author: aendenne
* Email: AutomateAnything@yahoo.com
* Create Date: April 21, 2007
* Last Modified Date: September 25,
2007
* Version: 1.1
*/
using
System;
using
System.Collections;
using
System.Collections.Generic;
using System.IO;
namespace YourNamespace.Tools
{
/// <summary>
/// Class that stores static methods to create,
access,
/// (especially read from) and manipulate files
/// </summary>
/// <remarks>
/// does NOT include good error-handling. this is
not a
/// recommended practice, please extend the
try/catch
statements...
/// i will post a simple error tool soon.
/// </remarks>
public
class FileTool
{
/// <summary>
/// string
constant to store message to return
/// if file
exists, and user does NOT wish to override
/// </summary>
private
const string
m_FileExistsMessage =
"The
file already exists: ";
/// <summary>
/// Gets
string indicating the current directory
/// </summary>
/// <returns>string
value of the current directory</returns>
public static
string
GetCurrentDirectory()
{
try
{
return
Directory.GetCurrentDirectory().ToString();
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return
null;
throw
(ex);
}
}
/// <summary>
/// Creates a
file in path suggested, and writes the
/// contents
to that file
/// </summary>
/// <param
name="path">
/// string
value indicating path (include file name)
/// to store
new file in
/// </param>
/// <param
name="contents">
/// string
value storing the contents to write
/// to the new
file
/// </param>
/// <param
name="overwrite">
/// bool value
indicating whether to replace file in path
/// if one
already exists at that location
/// </param>
public static
void
WriteNewFile(string path,
string
contents, bool overwrite)
{
try
{
CreateNewFile(path, overwrite);
AddToFile(path, contents, true);
}
catch (Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Creates a
file at the indicated path
/// </summary>
/// <param
name="path">
/// string
value indicating where to store
/// the new
file (include file name)
/// </param>
/// <param
name="overwrite">
/// bool value
indicating whether to replace file in path
/// if one
already exists at that location
/// </param>
/// <returns>
/// bool value
indicating whether file was created
/// </returns>
public static bool CreateNewFile(string path, bool overwrite)
{
try
{
if
(File.Exists(path)
&& !overwrite)
{
//Exception
ex = new Exception(m_FileExistsMessage);
//ErrorTool.ProcessError(ex);
return false;
}
FileStream
file = new FileStream(
path, FileMode.Create);
file.Close();
return true;
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return false;
throw(ex);
}
}
/// <summary>
/// Deletes
the file indicated from the system
/// </summary>
/// <param
name="path">
/// string
value indicating full file path to delete
/// </param>
private
static void
m_DeleteFile(string path)
{
try
{
if
(!File.Exists(path))
return;
File.Delete(path);
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Checks
path to be sure it's a file, and if so,
/// makes that
file writeable (may have been read-only...)
/// </summary>
/// <param
name="path">
/// string
path/filename to set as editable
/// </param>
private
static void
m_MakeEditable(string path)
{
try
{
if
(!File.Exists(path))
{
return;
//filepath doesn't exist
}
FileAttributes
attributes = File.GetAttributes(path);
if
((attributes & FileAttributes.Directory)
!= 0)
{
return;
//it's a directory/folder
}
attributes = FileAttributes.Normal;
File.SetAttributes(path,
attributes);
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Opens and
existing file, and adds to its contents
/// </summary>
/// <param
name="path">
/// string
value: full path/filename to add to
/// </param>
/// <param
name="appendage">
/// string
value: stream of characters/words to add
/// </param>
/// <param
name="newLine">
/// bool value
indicating whether to start at a new line
/// </param>
public static
void
AddToFile(string path,
string
appendage, bool newLine)
{
try
{
StreamWriter
writer = File.AppendText(path);
if
(newLine)
{
writer.WriteLine();
}
writer.Write(appendage);
writer.Close();
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Opens a
file and adds the supplied text
/// to that
file at the specified line number
/// </summary>
/// <param
name="path">
/// String
indicating the file path, including
/// the name
of the file
/// </param>
/// <param
name="textToInsert">
/// String to
insert/add to the file
/// </param>
/// <param
name="lineNumber">
/// Zero-based
line number----if the text should
/// be added
at line 10, then pass 9
/// </param>
public static
void
AddToFile(string path,
string
textToInsert, int lineNumber)
{
try
{
ArrayList
lines = GetLinesFromFile(path);
if
(lines.Count > lineNumber)
{
lines.Insert(lineNumber, textToInsert);
}
else
{
lines.Add(textToInsert);
}
StreamWriter
writer = new StreamWriter(path);
foreach
(string lineToWrite in
lines)
{
writer.WriteLine(lineToWrite);
}
writer.Close();
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Opens a
file and adds the supplied text
/// to that
file after the first line found,
/// that
contains the textToInsertAfter string.
/// Will add
at 0 (first line), if not found at all.
/// </summary>
/// <param
name="path">
/// String
indicating the file path, including
/// the name
of the file
/// </param>
/// <param
name="textToInsert">
/// String to
insert/add to the file
/// </param>
/// <param
name="textToInsertAfter">
/// Text to
place the new string after, will be
/// inserted
on the next line
/// </param>
public static
void
AddToFile(string path,
string
textToInsert, string
textToInsertAfter)
{
try
{
ArrayList
lines = GetLinesFromFile(path);
int
location = 0;
int
currentLine = 0;
foreach
(string lineToRead in
lines)
{
if
(lineToRead.Contains(textToInsertAfter))
{
location = currentLine
+ 1;
}
currentLine += 1;
}
lines.Insert(location,
textToInsert);
StreamWriter
writer = new StreamWriter(path);
foreach
(string lineToWrite in
lines)
{
writer.WriteLine(lineToWrite);
}
writer.Close();
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Opens and existing
file, and adds to its contents
/// (adds at
the end of prior contents)
/// </summary>
/// <param
name="path">
/// string
value: full path/filename to add to
/// </param>
/// <param name="appendage">
/// string
value: stream of characters/words to add
/// </param>
public static
void
AddToFile(string path, string
appendage)
{
try
{
if
(!File.Exists(path))
{
CreateNewFile(path, true);
}
AddToFile(path, appendage, true);
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Closes an
open FileStream object
/// </summary>
/// <param
name="fileToClose">FileStream to
close</param>
public static
void
CloseFile(FileStream
fileToClose)
{
try
{
fileToClose.Close();
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <remarks>
/// USES A METHOD FROM StringTool.cs!
/// Will not compile/execute without that file,
/// so remove/comment this method if you don't have
it
/// </remarks>
/// <summary>
/// Checks for
existence of a path
/// </summary>
/// <param
name="directoryPath">
/// string
value of path to check for
/// </param>
/// <returns>
/// bool value
indicating whether the requested path exists
/// </returns>
public static
bool
CheckForDirectory(string
directoryPath)
{
try
{
string
path = StringTool.GetFolderPath(directoryPath);
if (!Directory.Exists(path))
{
return
false;
}
else
{
return
true;
}
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <remarks>
/// USES A METHOD FROM StringTool.cs!
/// Will not compile/execute without that file,
/// so remove/comment this method if you don't have
it
/// </remarks>
/// <summary>
/// Creates a
directory (folder)
/// </summary>
/// <param
name="directoryPath">
/// string
value of path to create
/// </param>
public static
void
CreateDirectory(string directoryPath)
{
try
{
string
path = StringTool.GetFolderPath(directoryPath);
if (Directory.Exists(directoryPath))
{
return;
}
Directory.CreateDirectory(path);
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <remarks>
/// USES A METHOD FROM StringTool.cs!
/// Will not compile/execute without that file,
/// so remove/comment this method if you don't have
it
/// </remarks>
/// <summary>
/// Creates a
directory (folder) inside the path indicated
/// </summary>
/// <param
name="directoryPath">
/// string
value of path to create
/// </param>
/// <param
name="folderName">
/// string
name of the folder to create
/// </param>
public static
void
CreateDirectory(string directoryPath,
string
folderName)
{
try
{
string
path = StringTool.GetFolderPath(directoryPath);
path = path + folderName;
if
(Directory.Exists(directoryPath))
{
return;
}
Directory.CreateDirectory(path);
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Grabs an
ArrayList of lines from filepath indicated
/// </summary>
/// <param
name="path">
/// string
value of filepath to get lines from
/// </param>
/// <returns>
/// ArrayList
object containing each string line in the file
/// </returns>
public static
ArrayList
GetLinesFromFile(string path)
{
try
{
ArrayList
lines = new ArrayList();
StreamReader
reader = new StreamReader(path);
string
currentLine = string.Empty;
while
((currentLine = reader.ReadLine()) != null)
{
lines.Add(currentLine);
}
reader.Close();
return
lines;
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Grabs a
List of string lines from filepath indicated
/// </summary>
/// <param
name="path">
/// string
value of filepath to get lines from
/// </param>
/// <returns>
/// List
object containing each string line in the file
/// </returns>
public static
List<string> GetListOfLinesFromFile(string path)
{
try
{
List<string> lines = new
List<string>();
StreamReader
reader = new StreamReader(path);
string currentLine = string.Empty;
while
((currentLine = reader.ReadLine()) != null)
{
lines.Add(currentLine);
}
reader.Close();
return
lines;
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
/// <summary>
/// Grabs all
text from filepath indicated
/// </summary>
/// <param
name="path">
/// string
value of filepath to get text from
/// </param>
/// <returns>
/// string
(just one) of all text in file
/// </returns>
public static
string
GetFullFileText(string path)
{
try
{
StreamReader
reader = new StreamReader(path);
string
text = reader.ReadToEnd();
reader.Close();
return
text;
}
catch
(Exception ex)
{
//ErrorTool.ProcessError(ex);
//return;
throw
(ex);
}
}
}
}