nikorio nikorio - 21 days ago 5
C# Question

Avoid apostrophe with regex with event or saving to file

How to avoid writing into the richTextBox of saving into the file for apostrophe "

" and "
'
"

I also tried replace:

string text = File.ReadAllText(path);
text = text.Replace("’", "").Replace("'", "");
File.WriteAllText(path, text.ToLower());


But If file content is large program hangs with using in events. Also I have this
instead delete time after time.

So would be good to avoid writing of marks with writing or with saving into the file

Seems like I'm doing it wrong:

string toFile = String.Join(" ", richTextBox1.Lines);
var pat1 = @"\s?(’|')\s?";
var out1 = Regex.Replace(toFile, pat1, "");
File.WriteAllText(path, out1.ToLower());


so this way i lost lines if text is pasted and got whole text in one string.

but want get this result, if insert is:

Could’ve
Couldn’t
Didn’t
Doesn’t


I want write it to the file like this:

couldve
couldnt
didnt
doesnt

Answer

Try this:

System.Windows.Forms.OpenFileDialog oFile = new System.Windows.Forms.OpenFileDialog();

oFile.InitialDirectory = "c:\\" ;
oFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
oFile.FilterIndex = 2 ;
oFile.RestoreDirectory = true ;

if(oFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string file = oFile.Filename;
    string tmp = file + ".tmp";

    if (System.IO.File.Exists(tmp)) 
        System.IO.File.Delete(tmp);

    using(System.IO.StreamReader sr = new System.IO.StreamReader(file)) 
    using(System.IO.StreamWriter sw = new System.IO.StreamWriter(tmp, false, Encoding.ASCII ))
    {
        string line = null;
        while((line = sr.ReadLine()) != null)
            sw.WriteLine(line.Replace("’", "").Replace("'", ""));
    } 

    System.IO.File.Delete(file);
    System.IO.File.Move(tmp,  file);
}