Search code examples
c#iostreamreader

StreamReader not working as expected


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!


Solution

  • This is an encoing problem.

    I think you should change this line

    using (StreamWriter writer = new StreamWriter(filePath))
    

    To a variant that saves with the correct encoding (the overload that looks like this)

    using (StreamWriter writer = new StreamWriter(filePath, false, myEncoding))
    

    To get the correct encoding, where you have opened the file add this line

    myEncoding = reader.CurrentEncoding;