首页 > 解决方案 > 为什么我的 c# 函数只能以这种方式工作?

问题描述

我正在尝试用 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);
            }
        }
    }

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

不工作

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

并改变这一点,仅此而已:

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

标签: c#stringfunctionopenxml

解决方案


推荐阅读