在C#中VB的替换(str1,str2,str3)相当于什么?

时间:2018-05-24 20:13:05

标签: c# vb.net file

在VB和C#中,我知道当我们替换字符串时,我们使用:FILE.Replace并且我们不会将语句分配给变量。例如,File.Replace(text1, text2, text1);

但是,我有一个我想要使用的VB代码并将其转换为C#代码,我对如何使用Replace感到非常困惑。

VB代码工作正常!

这是VB代码:

    Dim pdfTemplate As String = Path.Combine(Application.StartupPath, "PDFs\2017-I9.pdf")
    pdfTemplate = Replace(pdfTemplate, "bin\Debug\", "")


    Dim fields = New Dictionary(Of String, String)() From {
      {"textFieldLastNameGlobal", Me.tbLast.Text},
      {"textFieldFirstNameGlobal", Me.tbFirst.Text},
      {"textFieldMiddleInitialGlobal", Mid(Me.tbMiddle.Text, 1, 1)},
      {"textFieldOtherNames", Me.tbOtherName.Text}
    }

pdfTemplate =替换(pdfTemplate," bin \ Debug \","")让我很困惑,我无法做到这一点。 t将其转换为C#。

顺便说一下,VB代码是在这里编写并发布的,但我忘了是谁。我想给作者一个功劳,即使我没有提及他/她。

以下是我尝试在C#中使用类似的代码

pdfTemplate = HostingEnvironment.MapPath("~/Content/PDFs/2017-I9.pdf");
pdfTemplate = File.Replace(pdfTemplate, "bin\\Debug\\", "");

        var fields = new Dictionary<string, string>()
        {
            {"textFieldLastNameGlobal", EL.LastName},
            {"textFieldMiddleInitialGlobal", EL.MiddleName},
            {"textFieldFirstNameGlobal", EL.FirstName},
            {"textFieldOtherNames", EL.OtherLastName}
        };

我在 pdfTemplate = File.Replace(pdfTemplate,&#34; bin \ Debug \&#34;,&#34;&#34;);

上收到错误

1 个答案:

答案 0 :(得分:2)

相当于VB Replace(str1, str2, str3)的C#代码是str1.Replace(str2, str3)

所以这一行:

pdfTemplate = Replace(pdfTemplate, "bin\Debug\", "")

应该成为这个:

pdfTemplate = pdfTemplate.Replace("bin\Debug\", "")

虽然这不正确,因为在C#中,字符串中的\字符会转义下一个字符,在这种情况下,C#编译器会抱怨无法识别的转义序列,以及换行符一个常量字符串,因为首先它不理解\D的含义,然后\"转义引号,这意味着它不会结束字符串。

你可以加倍反斜杠,或者在字符串前加@,这样就可以使用以下任何一种方法:

pdfTemplate = pdfTemplate.Replace(@"bin\Debug\", "");
pdfTemplate = pdfTemplate.Replace("bin\\Debug\\", "");

请注意,我还在语句末尾添加了分号。

警告字:对于路径操作,通常最好在.NET中使用Path类,因为它旨在正确处理路径错误

例如,如果您的文件名为Trashbin\Debug\File,那么您最终会得到TrashFile,这是不对的。

你可以这样做:

string templateFolder = Path.GetFullPath(Application.StartupPath);
if (templateFolder.EndsWith(@"\\bin\\debug", StringComparison.InvariantCultureIgnoreCase))
    templateFolder = Path.GetFullPath(Path.Combine(templateFolder, "..", ".."));
string templateFile = Path.Combine(templateFolder, "PDFs", "2017-I9.pdf");

如果您需要在Windows以外的其他操作系统上运行代码,则应使用Path类查找Debugbin以及其他操作系统可能使用正斜杠或冒号作为路径分隔符。

请注意,File.Replace执行的操作完全不同,它会替换文件,而不是字符串的内容。

相关问题