Search code examples
c#character-encoding

C# writes a ZERO WIDTH NO-BREAK SPACE at the beginning of a txt file


I have a text file that is written in C# using ascii encoding and when I attempt to read the file using a java project I get a ZERO WIDTH NO-BREAK SPACE character at the beginning of the file. Has anybody ever had this happen to them?

private static void SavePrivateKey(object key)
{
    if (logger.IsInfoEnabled) logger.Info("SavePrivateKey - Begin");
    string privatekey = (string)key;
    string strDirName = Utility.RCTaskDirectory;
    string strFileName = "PrivateKey.PPK";
    string strKeyPathandName = Path.Combine(strDirName, strFileName);

    //if (File.Exists(strKeyPathandName))
    //{
    //    File.Create(strKeyPathandName);
    //}

    if (!string.IsNullOrEmpty(privatekey))
    {//Save private key file
        if (!Directory.Exists(strDirName))
            Directory.CreateDirectory(strDirName);

        FileStream fileStream = new FileStream(strKeyPathandName, FileMode.OpenOrCreate);
        //TODO: Save File as ASCII
        using (StreamWriter sw = new StreamWriter(fileStream, Encoding.ASCII))
        {

            if (logger.IsDebugEnabled) logger.DebugFormat("Saving the private key to {0}.", strKeyPathandName);
            sw.Write(privatekey);

            sw.Close();
            if (logger.IsDebugEnabled) logger.DebugFormat("Saved private key to {0}.", strKeyPathandName);
        }
    }
    if (logger.IsInfoEnabled) logger.Info("SavePrivateKey() - End");
}

Solution

  • It seems that the text is written with a BOM which is usually done when you write Unicode files... this specific character is the BOM for UTF16 files, so there must be something in your C# writing this file as UTF16...

    see http://de.wikipedia.org/wiki/Byte_Order_Mark