我正在尝试拆分代表文件路径的 string
,因此该路径包含图片。例如,应该将路径字符串 #c:\users\common\pictures\2008
转换为 pictures\2008
。我遇到的问题是,当我在字符串中使用 \
时,它会给我一个错误。抱歉这个愚蠢的问题,我是 C# 新手。这是我到目前为止所做的:
string path = "#c:\users\common\pictures\2008";
string[] subs = path.Split('\');
int count = 0;
while(subs[count] != "pictures")
{
count++;
}
string newPath = "";
for (int i = count; i < subs.Length; i++)
{
newPath += "\" + subs[i];
}
Console.WriteLine(newPath);
答案 0 :(得分:4)
那是因为 \
是 C# 中的保留字符,所以你必须这样使用它 '\\'
如果是字符串,您可以在特殊字符 @
之前添加
如果是字符,您必须将其加倍 \\
string path = @"#c:\users\common\pictures\2008";
string[] subs = path.Split('\\');
int count = 0;
while (subs[count] != "pictures")
{
count++;
}
string newPath = "";
for (int i = count; i < subs.Length; i++)
{
newPath = Path.Combine(newPath ,subs[i]);
}
Console.WriteLine(newPath);
如果可能,也更喜欢使用 Path.Combine
,因为它会为您处理转义字符。
答案 1 :(得分:2)
首先,C# 将 '\' 字符视为字符串中的转义字符,因此您需要将其加倍才能工作。
string path = "#c:\\users\\common\\pictures\\2008";
string newPath = path.Substring(path.IndexOf("\\pictures\\") + 1);
这样做是从“\pictures\”开始之后的点开始获取“path”的子字符串(因为你不想要初始的“\”)。
或者这个:
string path = "#c:\\users\\common\\pictures\\2008";
string[] subs = path.Split('\\');
int count = Array.IndexOf(subs, "pictures");
string newPath = String.Join("\\", subs, subs.Length - count);
获取路径,拆分为文件夹数组,找到数组中元素的索引“pictures”,然后从该点开始加入数组。