ShareX/HelpersLib/Helpers/URLHelpers.cs

135 lines
No EOL
3.8 KiB
C#

#region License Information (GPL v3)
/*
ShareX - A program that allows you to take screenshots and share any file type
Copyright (C) 2007-2014 ShareX Developers
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/
#endregion License Information (GPL v3)
using HelpersLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace HelpersLib
{
public static class URLHelpers
{
public static string AddSlash(string url, SlashType slashType)
{
return AddSlash(url, slashType, 1);
}
public static string AddSlash(string url, SlashType slashType, int count)
{
if (slashType == SlashType.Prefix)
{
if (url.StartsWith("/"))
{
url = url.Remove(0, 1);
}
for (int i = 0; i < count; i++)
{
url = "/" + url;
}
}
else
{
if (url.EndsWith("/"))
{
url = url.Substring(0, url.Length - 1);
}
for (int i = 0; i < count; i++)
{
url += "/";
}
}
return url;
}
public static string GetFileName(string path, bool checkExtension = false)
{
if (path.Contains("/"))
{
path = path.Remove(0, path.LastIndexOf('/') + 1);
}
if (checkExtension && !Path.HasExtension(path))
{
return null;
}
return path;
}
public static string GetDirectoryPath(string path)
{
if (path.Contains("/"))
{
path = path.Substring(0, path.LastIndexOf('/'));
}
return path;
}
public static List<string> GetPaths(string path)
{
List<string> result = new List<string>();
string temp = string.Empty;
string[] dirs = path.Split('/');
foreach (string dir in dirs)
{
if (!string.IsNullOrEmpty(dir))
{
temp += "/" + dir;
result.Add(temp);
}
}
return result;
}
private static readonly string[] URLPrefixes = new string[] { "http://", "https://", "ftp://", "ftps://", "file://" };
public static bool HasPrefix(string url)
{
return URLPrefixes.Any(x => url.StartsWith(x, StringComparison.InvariantCultureIgnoreCase));
}
public static string RemovePrefixes(string url)
{
foreach (string prefix in URLPrefixes)
{
if (url.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase))
{
url = url.Remove(0, prefix.Length);
break;
}
}
return url;
}
}
}