c# - 如何从字符串中删除部分 "http://"?

标签 c#

我有这个方法:

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/

相关文章:

c# - String.Concat 中的双引号

c# - ASP.NET Core - 依赖注入(inject) - IdentityServer4 DbContext

c# - 温莎伐木设施 : Control log name

c# - 如何在单元格为空时在单元格中显示零

c# - 不能将静态方法指定为接口(interface)的一部分?

c# - LINQ删除错误(C#)

c# - Ninject:将某物绑定(bind)到自身是什么意思?

c# - 如何切换到特定文档的处理

c# - 单引号 (') and double quote (") ASP.NET 中的奇怪行为

c# - ASP.net MVC - 在复杂模型上更新模型