added IOPath double separator removal

This commit is contained in:
Timerix 2025-03-23 01:19:32 +05:00
parent dc35725b64
commit 386d71260c
3 changed files with 25 additions and 11 deletions

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<!--package info-->
<PackageId>DTLib</PackageId>
<Version>1.6.4</Version>
<Version>1.6.5</Version>
<Authors>Timerix</Authors>
<Description>Library for all my C# projects</Description>
<RepositoryType>GIT</RepositoryType>

View File

@ -15,29 +15,40 @@ public readonly struct IOPath
public IOPath(char[] path, bool separatorsFixed=false)
{
if (path.Length == 0)
throw new Exception("path is null or empty");
Str = separatorsFixed ? new string(path) : FixSeparators(path);
}
public IOPath(string path, bool separatorsFixed=false)
public IOPath(string path, bool separatorsFixed=false) : this(path.ToCharArray(), separatorsFixed)
{
if (path.IsNullOrEmpty())
throw new Exception("path is null or empty");
Str = separatorsFixed ? path : FixSeparators(path.ToCharArray());
}
static string FixSeparators(char[] path)
{
int length = path.Length;
if (path[length-1] == Path.Sep || path[length-1] == Path.NotSep)
char lastChar = path[path.Length - 1];
if (lastChar == Path.Sep || lastChar == Path.NotSep)
length--; // removing trailing sep
char[] fixed_path = new char[length];
StringBuilder sb = new StringBuilder();
bool prevWasSeparator = false;
for (int i = 0; i < length; i++)
{
if (path[i] == Path.NotSep)
fixed_path[i] = Path.Sep;
else fixed_path[i] = path[i];
{
// prevent double separators like this "a//b"
if(!prevWasSeparator)
sb.Append(Path.Sep);
prevWasSeparator = true;
}
else
{
sb.Append(path[i]);
prevWasSeparator = false;
}
}
return new string(fixed_path);
return sb.ToString();
}
public static IOPath[] ArrayCast(string[] a, bool separatorsFixed=false)

View File

@ -96,10 +96,13 @@ public static class Path
/// returns just dir name or file name with extension
public static IOPath LastName(this IOPath path)
{
if(path.Length < 2)
return path;
int i = path.LastIndexOf(Sep);
if (i == path.Length - 1) // ends with separator
i = path.LastIndexOf(Sep, i - 1);
if (i == -1) return path;
if (i == -1)
return path;
return path.Substring(i + 1);
}