StreamReader not working as expected

Posted by Jon Preece on Stack Overflow See other posts from Stack Overflow or by Jon Preece
Published on 2011-01-11T12:26:27Z Indexed on 2011/01/11 12:53 UTC
Read the original article Hit count: 211

Filed under:
|
|

Hi,

I have written a simple utility that loops through all C# files in my project and updates the copyright text at the top.

For example, a file may look like this;

//Copyright My Company, © 2009-2010

The program should update the text to look like this;

//Copyright My Company, © 2009-2010

However, the code I have written results in this;

//Copyright My Company, � 2009-2011

Here is the code I am using;

public bool ModifyFile(string filePath, List<string> targetText, string replacementText)
{
    if (!File.Exists(filePath)) return false;
    if (targetText == null || targetText.Count == 0) return false;
    if (string.IsNullOrEmpty(replacementText)) return false;

    string modifiedFileContent = string.Empty;
    bool hasContentChanged = false;

    //Read in the file content
    using (StreamReader reader = File.OpenText(filePath))
    {
        string file = reader.ReadToEnd();

        //Replace any target text with the replacement text
        foreach (string text in targetText)
            modifiedFileContent = file.Replace(text, replacementText);

        if (!file.Equals(modifiedFileContent))
            hasContentChanged = true;
    }

    //If we haven't modified the file, dont bother saving it
    if (!hasContentChanged) return false;

    //Write the modifications back to the file
    using (StreamWriter writer = new StreamWriter(filePath))
    {
        writer.Write(modifiedFileContent);
    }

    return true;
}

Any help/suggestions are appreciated. Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about io