【发布时间】:2014-11-02 23:21:27
【问题描述】:
我正在将二进制文件转换为文本并将其转储为 PDF。我有这个工作,但我需要生成与另一个程序的某些示例相同的输出(它生成文本,然后将其转换为二进制,所以我想我正在转换回来?)。
除了一件事之外,我得到了相同的输出。我应该有一堆破折号来衬托主题标题,但我得到了问号 (?)。如果我使用 Notepad++ 显示二进制文件,问号会变成一些随机的韩文字符 (컴)。我尝试过result.Replace("?", "-"); 和result.Replace("컴", "-");,我什至尝试过检查Contains(),但没有任何触发。
如何替换它们?
不确定它是否会有所帮助,但这是我的代码:
private void btnConvertBinaryToPDF_Click(object sender, EventArgs e)
{
PdfDocument document = new PdfDocument(); //make new pdf document
PdfPage page = document.AddPage(); //add a page to the document
XGraphics gfx = XGraphics.FromPdfPage(page); //use this to draw/write on the specified page
XFont font = new XFont("Courier New", 10); //need a font to write with
string result = "";
string path = @"C:\Users\file";
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
FileStream fs = File.OpenRead(path);
int i = 1;
while (fs.Read(b, 0, b.Length) > 0)
{
string tmp = temp.GetString(b);
result += tmp;
b = new byte[1024]; //clear the buffer
}
if (result.Contains("?"))
{
Console.WriteLine("contains!");
}
result.Replace("컴", "-");
XTextFormatter tf = new XTextFormatter(gfx);
XRect rect = new XRect(40, 100, 500, 100);
tf.DrawString(result, font, XBrushes.Black, rect, XStringFormats.TopLeft);
string filename = "HelloWorld.pdf"; //make the filename
document.Save(filename); //save the document to the filename
Process.Start(filename); //open the file to show the document
}
编辑:path 包含二进制数据。我需要获取其内容的文本表示。以上工作正常,除了编号高于 127 的 ASCII 字符。
【问题讨论】:
-
问号往往是由文本编码问题引起的。这开始很糟糕,utf-8 是一种可变长度编码。您使用 FileStream 的方式将切断编码字符的部分字节。您必须使用 StreamReader 来读取文件。
标签: c# text unicode binary converter