亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我無法讀取所有 Rtf 文件內容

我無法讀取所有 Rtf 文件內容

C#
慕婉清6462132 2023-09-24 11:40:55
我有一個 Rtf 文件,我需要讀取文件來解析。文件中有一些特殊字符,因為文件中有圖像。當我從文件中讀取所有文本時,無法讀取特殊字符后面的內容。ReadAllText我嘗試使用withEncoding.UTF8和讀取文件Encoding.ASCIIpublic class ReadFile{    public static string GetFileContent(string path)    {        if (!File.Exists(path))        {            throw new FileNotFoundException();        }        else        {            // I also tried             // return File.ReadAllText(path, Encoding.ASCII);            string text = string.Empty;            var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))            {                string line;                while ((line = streamReader.ReadLine()) != null)                {                    text += line;                }            }            return text;        }    }}實際上我的結果是所有文本,直到開始特殊字符。{\rtf1\ansi\ansicpg1252\deff0\deftab720{\fonttbl{\f0\fnil Times New Roman;}{\f1\fnil Arial;}}{\colortbl;\red000\green000\blue000;\red255\green000\blue000 ;\red128\green128\blue128;}\paperw11905\paperh16837\margl360\margr360\margt360\margb360 \sectd \sectdefaultcl \marglsxn360\margrsxn360\margtsxn360\margbsxn360{ *\do\dobxpage\dobypage\do dhgt819 2\dptxbx{\dptxbxtext\ pard\plain {\pict\wmetafile8\picw19499\pich1746\picwgoal1305695\pichgoal116957\bin342908Rtf 文件在這里
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

我做了。為了讀取我使用的文件File.ReadAllBytes(path)并在結果變量中,我將字節 0 替換為 (nul),將字節 27 替換為 esc。


byte[] fileBytes = File.ReadAllBytes(path);


StringBuilder sb = new StringBuilder();

foreach (var b in fileBytes)

{

? ? // handle printable characters

? ? if ((b >= 32) || (b == 10) || (b == 13) || (b == 9)) // lf, cr, tab

? ? ? ? sb.Append((char)b);

? ? else

? ? {

? ? ? ? // handle control characters

? ? ? ? switch (b)

? ? ? ? {

? ? ? ? ? ? case 0: sb.Append("(nul)"); break;

? ? ? ? ? ? case 27: sb.Append("(esc)"); break;

? ? ? ? ? ? ? ? // etc.

? ? ? ? }

? ? }

}


return sb.ToString();


查看完整回答
反對 回復 2023-09-24
  • 1 回答
  • 0 關注
  • 106 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號