我有这个方法:
private List<string> offline(string targetDirectory)
{
if (targetDirectory.Contains("http://"))
{
MessageBox.Show("true");
}
DirectoryInfo di = new DirectoryInfo(targetDirectory);
List<string> directories = new List<string>();
try
{
string[] dirs = Directory.GetDirectories(targetDirectory,"*.*",SearchOption.TopDirectoryOnly);
for (int i = 0; i < dirs.Length; i++)
{
string t = "http://" + dirs[i];
directories.Add(t);
}
}
catch
{
MessageBox.Show("hgjghj");
}
return directories;
}
这是部分:
if (targetDirectory.Contains("http://"))
{
MessageBox.Show("true");
}
我得到一个目录,其中包含该目录中的所有目录,我正在向每个目录添加字符串 "http://"
。
问题是下一次目录访问函数时会出现 "http://"
例如:http://c:\\
或 http://c:\\windows
然后是行
DirectoryInfo di = new DirectoryInfo(targetDirectory); // throws exception.
所以我希望每次目录进入函数时检查它是否以 "http://"
开头,去掉 "http://"
部分,获取所有的目录,然后像现在一样给每个目录添加"http://"
。
如何删除 "http://"
?
最佳答案
我会比使用 Contains
更严格 - 我会使用 StartsWith
,然后是 Substring
:
if (targetDirectory.StartsWith("http://"))
{
targetDirectory = targetDirectory.Substring("http://".Length);
}
或者用辅助方法包装它:
public static string StripPrefix(string text, string prefix)
{
return text.StartsWith(prefix) ? text.Substring(prefix.Length) : text;
}
老实说,我不清楚为什么要将 http://
作为前缀。我不明白您如何期望以 http://
为前缀的目录名称是有效的 URL。或许如果您能解释您这样做的原因,我们可以建议更好的方法。
(此外,我真的希望您在实际代码中没有像这样的 try/catch block ,并且通常您遵循 .NET 命名约定。)
关于c# - 如何从字符串中删除部分 "http://"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13062414/