如何将文本插入字符串中的占位符?

How to insert text into placeholder in a string?

我正在尝试将 Environment.UserName 放入我的 Process.Start 调用的路径中,下面是我目前拥有的代码:

private void viewButton_Click(object sender, EventArgs e)
{
    Process.Start(@"C:\Users\{0}\Documents\Content\New folder", Environment.UserName);
}

如何将 {0} 替换为 Environment.UserName?

在评论中讨论后,问题是他想将 Environment.UserName 放在路径中 {0} 的内部。

因此,话虽如此,他要求使用内插逐字字符串 (https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/string-interpolation#:~:text=An%20interpolated%20verbatim%20string%20starts,%22%20or%20%22%7D%7D%22.),如下所示:

$@"C:\Users\{Environment.UserName}\Documents\Content\New folder"

您最初的问题是如何替换字符串中的占位符。 对于这个 ConnorTJ 的回答非常好。内插字符串是首选方法。

string s = $"The current users name is {Environment.UserName}.";

或者您可以使用 string.Format:

string s = string.Format("The current users name is {0}.", Environment.UserName);

但正如其他人已经提到的,有更好的方法来检索系统文件夹。要获取文档文件夹,您最好使用

string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

要添加子文件夹,请使用 System.IO.Path.Combine():

string folder = Path.Combine(docFolder, @"Content\New folder");

启动一个进程并只传递一个文件夹是可行的,因为它会打开分配给文件夹的应用程序,很可能是 Windows Explorer。无论如何,如果您想确保 Windows Explorer 将打开,我建议您明确启动 Explorer 并将文件夹作为参数传递:

Process.Start("explorer.exe", folder);