0

I have many files contains some string. I want to replace this string with another value in all these files.

The files may have different encodings and extentions.

So, I'm using next method for all files

void ReplaceInFile(string file, string oldValue, string newValue)
{
 string text = File.ReadAllText(file);
 text = text.Replace(oldValue, newValue);
 File.WriteAllText(file, text);
}

But I'm not sure I will not broke some of them, which has some unusual encoding. Am I right?

What else I can use to do this operation for files with different encodings?

How can I check that nothing broken?

7
  • I assume this means you don't have any way of knowing/checking which encoding each specific file has? Commented Apr 1, 2014 at 12:44
  • It's simply not safe to change text when you don't know its encoding. If you read in a file with an unknown encoding, you may get an exception or some of the characters may be changed to other characters. Commented Apr 1, 2014 at 12:44
  • 1
    If you have the wrong encoding then it will probably not find the oldValue. If it does not find the oldValue then don't save. Even if you do find the oldValue that does not guarantee you have the correct encoding. Commented Apr 1, 2014 at 12:55
  • If there any way to get encoding somehow..? If no, then no, I don't know the encoding for file. Commented Apr 1, 2014 at 12:56
  • Sort of. blogs.msdn.com/b/oldnewthing/archive/2007/04/17/2158334.aspx Commented Apr 1, 2014 at 13:01

1 Answer 1

1

You have to know the encoding of the file in order to interpret the data correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.