-3

I need to read a file in specific location and find all the occurence of single quote and replace it by &#39 in c#

string file = @"D:\MyDirectory\MyFile.po";

Say this is my file, I have to read this and replace all single quote by &#39.

Shesha
  • 1,857
  • 6
  • 21
  • 28
  • Please include the code you have written to attempt this and tell us what's not working – Wim Ombelets Apr 12 '16 at 11:16
  • 6
    Duplicate! This question has been answered at least 4 times on stackoverflow: http://stackoverflow.com/questions/13509532/how-to-find-and-replace-text-in-a-file-with-c-sharp http://stackoverflow.com/questions/1915632/open-a-file-and-replace-strings-in-c-sharp http://stackoverflow.com/questions/19615624/c-sharp-replace-string-in-a-text-file and http://stackoverflow.com/questions/27239095/replacing-a-certain-word-in-a-text-file – bitbonk Apr 12 '16 at 11:17

1 Answers1

4

You can use the System.IO Library, and read it into an array, replace each instance and then write it back to the file

string file = @"D:\MyDirectory\MyFile.po";
string[] allLines = System.IO.File.ReadAllLines(file);
for(int i = 0; i < allLines.GetLength(0); i++)
{
    allLines[i] = allLines[i].Replace("'",@"&#39");
}
System.IO.File.WriteAllLines(file,allLines);

Alternatively you can use ReadAllText, which returns the entire file's contents as a single string, which removes the requirement to loop

string file = @"D:\MyDirectory\MyFile.po";
string allText = System.IO.File.ReadAllText(file);
allText = allText.Replace("'",@"&#39");
System.IO.File.WriteAllText(file,allText);
Alfie Goodacre
  • 2,753
  • 1
  • 13
  • 26
  • @Default Yes sorry, my mistake! All are fixed now - I was a little absent minded and it was off the top of my head :) – Alfie Goodacre Apr 12 '16 at 11:26
  • 1
    second example is simplier, but in case of large file, it could lead to performance issues. – Nino Apr 12 '16 at 11:40