[英]Replace SOH character in string
我正在閱讀一個小的MSWord文檔,並將其內容存儲在字符串中。
此字符串中包含SOH特殊字符。 在將它們寫入新文本(.txt)文件之前,我想用一個占位符字符串(例如“#placeholder1”)替換它們。 請注意,我不想修改/編輯MSWord文檔
我不確定string.Replace是否適合此情況,或者我是否需要走其他路線。 它可能只是我用於SOH字符的參數。
建議?
沒有理由為什么您的工作不起作用。 這是一個可以在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
的調用結果。
您可以使用以下功能來讀取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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.