我有这个方法:
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:\\
or 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 块,并且通常您遵循 .NET 命名约定。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)