-
April 10th, 2009, 07:30 AM
#1
Replacing strings in text files with C#
Upon searching for a way to replace occurences in text files, I only found methods that had to read the entire text file into the memory. These methods cannot be used for large files. That's why I have created this method:
Code:
/*
* This method will replace all occurences of 'search' with 'replace' in the file with URI 'filepath' and backup the
* original file to the 'backup' URI.
* If 'ignoreEndsOfLine' is true, the method will also replace occurences that are split over
* multiple lines in the text. In that case, the file will also be rewritten on a single line.
*/
public static void replaceInTextFile(string filepath, string search, string replace, bool ignoreEndsOfLine, string backup) {
if (search == "" || search == null)
{
throw new ArgumentException("'search' cannot be null or an empty string", "search");
}
StreamReader sr = new StreamReader(filepath);
StreamWriter sw = new StreamWriter("TEMP" + filepath);
char[] buffer = new char[search.Length];
for (int i = 0; i < buffer.Length; i++) {
buffer[i] = (char)0;
}
while (sr.Peek() != -1)
{
if (new string(buffer) == search)
{
sw.Write(replace);
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (char)0;
}
}
else
{
if (buffer[0] != (char)0)
{
sw.Write(buffer[0]);
}
for (int i = 0; i < buffer.Length; i++)
{
if (i < buffer.Length - 1)
{
buffer[i] = buffer[i + 1];
}
else
{
while (((char)sr.Peek() == (char)10 || (char)sr.Peek() == (char)13) && ignoreEndsOfLine)
{
sr.Read();
}
buffer[i] = (char)sr.Read();
}
}
}
}
if (new string(buffer) == search)
{
sw.Write(replace);
}
else
{
for (int i = 0; i < buffer.Length; i++)
{
if (buffer[i] != (char)0)
{
sw.Write(buffer[i]);
}
}
}
sr.Close();
sw.Close();
FileInfo fi = new FileInfo("TEMP" + filepath);
fi.Replace(filepath, backup, true);
}
I hope you can use and test this method of replacing strings in a text file. Please let me know when there are bugs in the method so that I can further develop it.
Last edited by Shuja Ali; April 10th, 2009 at 08:34 AM.
Reason: added code tags
-
April 10th, 2009, 07:35 AM
#2
Re: Replacing strings in text files with C#
Please let me know when there are bugs in the method so that I can further develop it.
Let me get this right : you want the forum to unit test your code ?
I'd suggest you learn to do this by yourself : download NUnit to get started.
Darwen.
-
April 10th, 2009, 08:35 AM
#3
Re: Replacing strings in text files with C#
Looks like it is a kind of tip that he wants to post. You should rather post it as a Tip on the Codegurus main page.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|