2011-09-01 22 views
1

我有一個要打開的RTF文件,請替換字符串「TEMPLATE_Name」並保存。但保存後,文件無法再正確打開。當我使用MS Word時,文件將打開並顯示RTF原始代碼,而不是文本。將RTF編輯爲純文本,但無法再次打開

恐怕我打破了格式或編碼,但我真的不知道如何:

 using (MemoryStream ms = new MemoryStream(1000)) 
     using (StreamWriter sw = new StreamWriter(ms,Encoding.UTF8)) 
     { 
      using (Stream fsSource = new FileStream(Server.MapPath("~/LetterTemplates/TestTemplate.rtf"), FileMode.Open)) 
      using (StreamReader sr = new StreamReader(fsSource,Encoding.UTF8)) 
       while (!sr.EndOfStream) 
       { 
        String line = sr.ReadLine(); 
        line = line.Replace("TEMPLATE_Name", model.FirstName + " " + model.LastName); 
        sw.WriteLine(line); 
       } 

      ms.Position = 0; 

      using (FileStream fs = new FileStream(Server.MapPath("~/LetterTemplates/test.rtf"), FileMode.Create)) 
       ms.CopyTo(fs); 
     } 

什麼可能是問題的任何想法?

謝謝。

解決方案:一個問題是@BrokenGlass指出的事實,我沒有沖洗流。另一個是編碼。在RTF文件的拳頭線,我可以看到:

{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\ 

因此,即使不理解有關RTF任何東西,我將編碼設置爲1252代碼頁和它的工作原理:

 using (MemoryStream ms = new MemoryStream(1000)) 
     using (StreamWriter sw = new StreamWriter(ms,Encoding.GetEncoding(1252))) 
     { 
      using (Stream fsSource = new FileStream(Server.MapPath("~/LetterTemplates/TestTemplate.rtf"), FileMode.Open)) 
      using (StreamReader sr = new StreamReader(fsSource,Encoding.GetEncoding(1252))) 
       while (!sr.EndOfStream) 
       { 
        String line = sr.ReadLine(); 
        line = line.Replace("TEMPLATE_Name", model.FirstName + " " + model.LastName); 
        sw.WriteLine(line); 
       } 

      sw.Flush(); 
      ms.Position = 0; 

      using (FileStream fs = new FileStream(Server.MapPath("~/LetterTemplates/test.rtf"), FileMode.Create)) 
       ms.CopyTo(fs); 
     } 
+2

爲什麼不直接寫入磁盤而是先寫入內存? – SLaks

+0

因爲意圖是將流發送到另一個組件,所以這只是一個概念問題的教授。 – vtortola

回答

4

StreamWriter是緩衝內容 - 確保您在從內存流中讀取數據之前先致電sw.Flush()

StreamWriter.Flush()

清除當前作家所有緩衝區並使所有緩衝的數據 被寫入到基礎流。

編輯在評論光:

一個更好選擇,因爲@leppie提到的重組代碼中使用using塊強制沖洗,而不是明確地做這件事:

using (MemoryStream ms = new MemoryStream(1000)) 
{ 
    using (StreamWriter sw = new StreamWriter(ms,Encoding.UTF8)) 
    { 
    //... 
    } 
    ms.Position = 0; 
    //Write to file 
} 

甚至更​​好備選方案,因爲@Slaks指出直接寫入文件並且根本不使用內存流 - 除非t這裏有其他原因,你這樣做,這似乎是最直接的解決方案,它會簡化你的代碼,並避免在內存中緩衝文件。

+1

處理調用'關閉',然後調用'Flush'。 – leppie

+2

他在'StreamWriter'的使用區塊內部使用了內存流 - 它沒有被刷新。 – BrokenGlass

+1

哎呀抱歉!我沒有想到! +1銳利的眼睛:) – leppie