2

The code I'm trying to write is to replace a string of words within a text file. Though I'm able to read the file's content to console, I'm unable to replace the string of words and write a new string to the file.

Here's my code:

private static void filesys_created (object sender, FileSystemEventArgs e)
{
    using (StreamReader sr = new StreamReader(e.FullPath))
    {
        Console.WriteLine(sr.ReadToEnd());
        File.ReadAllText(e.FullPath);
        sr.Close();
    }

    using (StreamWriter sw = new StreamWriter(e.FullPath))
    {
        string text = e.FullPath.Replace("The words I want to replace");
        string newtext = "text I want it to be replaced with";

        sw.Write(e.FullPath, text);
        sw.Write(newtext);
        sw.Close();
    }
}

The problem is that the .Replace is deleting everything in the text file and only inserting the path of the directory.

EpicKip
  • 4,015
  • 1
  • 20
  • 37
s4mdev
  • 27
  • 6

2 Answers2

6

Well, the problems as I see it are a) you're reading the file but not assigning the text to a variable b) you're not actually doing a replace and c) you are indeed writing the file name to the output.

You don't need to use streams so your code can be simplified to this:

var contents = File.ReadAllText(e.FullPath);
contents = contents.Replace(text, newText);
File.WriteAllText(e.FullPath, contents);

It looks like you're using a FileSystemWatcher to pick up the file, so just noting that this will fire (at least) a Changed event.

stuartd
  • 70,509
  • 14
  • 132
  • 163
0

You are writing the FullPath into the file, try this:

var text = null;
using (StreamReader sr = new StreamReader(e.FullPath))
{
    text = sr.ReadToEnd();
    Console.WriteLine(text);
}

using (StreamWriter sw = new StreamWriter(e.FullPath))
{
    var replaced = text.Replace("The words I want to replace", "text I want it to be replaced with");
    sw.Write(replaced);
}
Péter Csajtai
  • 878
  • 6
  • 9