C#:将变量插入文本文件

C#: Inserting Variable into Text File

总结:我想将变量插入到一个文本文件中。我试着环顾四周,但无济于事。也许我正在使用错误的关键字进行搜索。我知道将变量插入到字符串中,它很简单:

string str1 = "hello {0}";
string str2 = "world";
string final = string.Format(str1, str2); //Output should be "hello world"

按照同样的思路,我制作了一个str1的文本文件,将文本文件加载到一个字符串变量中,重复上述过程。

str1.txt:

hello {0}

代码:

string str1 = System.IO.File.ReadAllText(@"..\..\str1.txt"); //Should load the text file as a string
string str2 = "world"
string final = string.Format(str1, str2); //Output should be "hello world"

现在,我在调用 string.Format 时收到 'Input string was not in a correct format' 错误,我不太清楚为什么。

编辑:我猜我没有提供足够的信息。对不起!我试图插入变量的文本文件是一个 class 的文本文件,在不同的点插入了 {0}、{1}、...。

我 运行 你的代码示例在我的机器上,它按你期望的方式工作。我建议您查看 str1.txt 文件的内容并确认路径正确解析。如果 none 有效,请查看文件的编码。

还要注意文件中的杂散 {} 字符。通过将它们加倍或用

替换您的代码来逃避它们
string str1 = "hello {0}";
string str2 = "world";
string final = str1.replace("{0}", str2); //Output should be "hello world"

ReadAllText() 可能给你一个字符串文字,所以 {0} 实际上是 \{0\} 并且不会按预期运行。 string.Format() 然后抛出异常,因为第一个字符串没有放置第二个参数的有效位置。

确保 str1 中有一个占位符标记。它需要 {0} 才能知道将 str2 插入 str1 的位置。