2013-05-13 810 views
2

我正在读取一个小的MSWord文档并将其内容存储在一个字符串中。替换字符串中的SOH字符

此字符串中包含SOH特殊字符。我想在将它们写入新文本(.txt)文件之前用占位符字符串替换它们,如“#placeholder1”。请注意,我不想修改/编辑MSWord文档

我不确定是否string.Replace会适合这种情况,或者如果我需要去不同的路线。它可能只是我用于SOH角色的参数。

对此提出建议?

+0

你是如何代表SOH字符? – 2013-05-13 16:50:54

+0

\ x01是我目前正在使用的 – 2013-05-13 16:53:02

+0

我本来期望能够工作,但可以用'\ u0001'尝试。请参阅[这些文档](http://msdn.microsoft.com/en-us/library/aa664669%28v=VS.71%29.aspx)。你的搜索字符串中还有什么东西可能会被误认为是逃生序列的一部分? – 2013-05-13 16:58:12

回答

6

没有理由为什么你在做什么不应该工作。这里有一个小例子,你可以ideone测试:

using System; 
public class Test 
{ 
    public static void Main() 
    { 
     String s = "\u0001 This is a test \u0001"; 
     s = s.Replace("\u0001","Yay!"); 
     Console.WriteLine(s); 
    } 
} 

我想你可能是做错了唯一的其他东西,不储存您的来电Replace的结果。

+0

这实质上就是我所拥有的。来看看,虽然它看起来可能是我正在阅读的单词文件的问题。我用其他地方的副本替换它,替换现在可用。有趣的是在这两个文件的ASCII输出中是一样的... [1] [11] [13] [1] [13] 我虽然接受这个作为回答,因为它肯定是正确的。感谢你的帮助James! – 2013-05-13 17:28:48

+0

感谢您的接受。我觉得有助于提出一个最小的例子,因为它可以缩小问题的根源。在这种情况下,显然不是错误的“替换”。 – 2013-05-13 17:36:14

0

您可以使用下面的函数读取Microsoft Word文档的内容(需要参考Microsoft.Office.Interop.Word):

public string ReadWordDoc(string Path) 
{ 
    // microsot word app object 
    Microsoft.Office.Interop.Word.Application _objWord=null; 

    // microsoft word document object 
    Microsoft.Office.Interop.Word.Document _objDoc= null; 

    // obj missing value (ms office) 
    object _objMissing = System.Reflection.Missing.Value; 

    // string builder object to hold doc's content 
    StringBuilder _sb = new StringBuilder(); 

    try 
    { 
     // create new word app object 
     _objWord= new Microsoft.Office.Interop.Word.Application(); 

     // check if the file exists 
     if (!File.Exists(Path)) throw (new FileNotFoundException()); 

     // full path to the document 
     object _objDocPath = Path; 

     // readonly flag 
     bool _objReadOnly = true; 

     // open word doc 
     _objDoc = _objWord.Documents.Open(
      ref _objDocPath, 
      ref _objMissing, 
      _objReadOnly, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing, 
      ref _objMissing); 

     // read entire content into StringBuilder obj 
     for (int i = 1; i <= _objDoc.Paragraphs.Count; i++) 
     { 
      _sb.Append(_objDoc.Paragraphs[i].Range.Text.ToString()); 
      _sb.Append("\r\n"); 
     } 

     // return entire doc's content 
     return _sb.ToString(); 
    } 
    catch { throw; } 
    finally 
    { 
     _sb = null; 

     if (_objDoc != null) { _objDoc.Close(); } 
     _objDoc = null; 

     if (_objWord != null) { _objWord.Quit(); } 
     _objWord = null; 
    } 
}