为什么我的c#函数只能以这种方式工作?

时间:2018-05-11 21:24:38

标签: c# string function openxml

我正在尝试用Open XML SDK替换docx文件上的文本,它工作正常,所以它替换它,因为我写“hi”和单词“hello”将它们直接传递给regexText.Replace,如下所示:

  

工作

public static void SearchAndReplace(string document, string find, string replaced)
    {
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
        {
            string docText = null;
            using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
            {
                docText = sr.ReadToEnd();
            }

            Regex regexText = new Regex("hi");
            docText = regexText.Replace("hello");

            using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
                sw.Write(docText);
            }
        }
    }

但是当我尝试使用传递的变量调用函数时,代码不会将单词“hi”替换为“hello”,但为什么呢?什么是更改代码使其失败? (我的意思是代码正在编译,它不会抛出任何异常,但它不会替换)

  

不工作

SearchAndReplace("template.docx", "hi", "hello");

并改变这一点,没有别的:

Regex regexText = new Regex(find);
docText = regexText.Replace(docText, replace);

0 个答案:

没有答案
相关问题