问题
In my code
string[] Lines = reactor.GetMergedLines();
string fileName = "foo.bar";
StreamWriter sw = new StreamWriter(File.Open(fileName, FileMode.CreateNew), Encoding.GetEncoding(28605));
foreach (string line in Lines)
{
sw.WriteLine(line);
}
sw.Close();
the file, which gets created is not encoded with the given codepage. Lines is filled with strings out of an iso-8859-1-file. I tried it with the code page number Encoding.GetEncoding(28605)
, it's name Encoding.GetEncoding("ISO-8859-15")
and with File.WriteAllLines(fileName, Lines, Encoding.GetEncoding(28605))
instead of StreamWriter. But if I take a look at the file with cygwin file -bi [filename]
, it tells me, the encoding would be "us-ascii". Also, some characters aren't encoded properly and replaced by question marks.
How to write out a text file in C# with a code page other than utf-8? didn't helped, as you can see.
What is the problem?
回答1:
You can use other overloads of Encoding.GetEncoding
to handle all cases when an Unicode character can't be converted to your target code page. More information on this MSDN topic.
The same could be achieved if you explicitly set the Encoding.EncoderFallback
property (link to MSDN).
For example you can use the following to throw an exception every time when conversion of one Unicode character fails:
Encoding enc = Encoding.GetEncoding(28605, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
Note: The default EncoderFallback
is System.Text.InternalEncoderBestFitFallback
which produces question marks for unknown code points.
来源:https://stackoverflow.com/questions/22982718/file-encoding-doesnt-work