0

I'm working on a simple tool that loads a text file and does several regex search and replaces when hitting a button. This all works without problem. I have a textbox to preview the text after f&r and it all looks solid in there.

However, when i save my file as .txt and then open it suddenly begins with these characters æ- (those are the very first characters in the entire file and the only ones I don't want).

I thought it may be an encoding error as I'm pretty positive that it's not the sideproduct of 1 of the replaces.

I've tried searching for people with a similar issue but couldn't find an answer. I'm very new to C#, normally I do this stuff in Notepad++ but I wanted to try building a simple tool around a Notepad++ macro.

            SaveFileDialog sfd = new SaveFileDialog();
        sfd.Title = "Save file";
        sfd.Filter = "TXT files|*.txt";
        sfd.InitialDirectory = @"C:\temp";
        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string path = sfd.FileName;
            BinaryWriter bw = new BinaryWriter(File.Create(path));

            bw.Write(textBox1.Text);
            bw.Dispose();
        }

Does it have anything with the saving of the file itself? Forgive me if this is some kind of rookie mistake. Any help is appreciated. Thanks.

Peter
  • 69
  • 8
  • 1
    Why do you use a BinaryWriter and not a TextWriter? – Jean-Claude Colette Oct 10 '16 at 22:04
  • 2
    Or even `File.WriteAllText(path, s)` – SimpleVar Oct 10 '16 at 22:04
  • 1
    `File.WriteAllText` is the simple way to write text to file as @simplevar pointed out. The reason you have weird characters at the beginning of the text file is because [`BinaryWriter.Write(string)`](https://msdn.microsoft.com/en-us/library/yzxa6408(v=vs.110).aspx) writes the length (in bytes) of the string to the beginning which is NOT standard for a text file, so anything that decodes text will decode those bits as if they represent a character even though they don't. – Quantic Oct 10 '16 at 22:17
  • Looks like you should have started with this search: https://stackoverflow.com/search?q=%5Bc%23%5D+how+to+write+a+text+file%3F. See the marked duplicate for one of the many useful, pertinent answers. – Peter Duniho Oct 11 '16 at 03:01

0 Answers0