在 c# 中,您可以通过字符串插值或 string.format 方法将变量引用到文件路径中。字符串插值使用 ${} 语法,而 string.format 方法需要提供格式字符串和要插入的变量。例如:string filepath = $"c:users{username}documentsmyfile.txt";
如何引用 C# 文件路径中变量
在 C# 中,您可以使用字符串插值或 String.Format 方法,将变量引用到文件路径中。
字符串插值
字符串插值是 C# 6.0 中引入的一种简洁语法,它允许您将表达式直接嵌入到字符串文字中。要使用字符串插值,请使用 ${} 语法:
string path = $"C:Users{username}Documentsmyfile.txt";
String.Format 方法
String.Format 方法是一种更传统的方法,用于将变量格式化为字符串。您需要提供一个格式字符串和要插入的值:
string path = String.Format("C:Users{0}Documentsmyfile.txt", username);
示例
以下是一个将变量引用到文件路径中的示例:
string username = "JohnDoe";
string filePath = @"C:Users" + username + @"Documentsmyfile.txt";
// 或者使用字符串插值
string filePath = $"C:Users{username}Documentsmyfile.txt";
// 或者使用 String.Format 方法
string filePath = String.Format(@"C:Users{0}Documentsmyfile.txt", username);