C# 在 txt 文件的开头写入一个 ZERO WIDTH NO-BREAK SPACE

GEv*_*ing 2 c# java character-encoding

我有一个使用 ascii 编码用 C# 编写的文本文件,当我尝试使用 java 项目读取该文件时,我在文件开头得到一个ZERO WIDTH NO-BREAK SPACE字符。有人遇到过这种情况吗?

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");
}
Run Code Online (Sandbox Code Playgroud)

Yah*_*hia 5

看起来文本是用 BOM 编写的,这通常是在编写 Unicode 文件时完成的...这个特定字符是 UTF16 文件的 BOM,因此您的 C# 中一定有某些东西将此文件写入为 UTF16...

请参阅http://de.wikipedia.org/wiki/Byte_Order_Mark