Reputation: 545
I'm grabbing product versions from DB which stores as VARCHAR
and has value something like this 2.6.12-build.222
. I need to trim everything after -
so the result is 2.6.12
below is the code how I'm doing this string operation and working perfectly fine, I'm getting trimmed version but I need to compare two versions for the further operations for that I'm using Version
class but as soon as I pass my substring to Version class it's showing me this error-
ArgumentException: Version string portion was too short or too long.
All my versions are in 2.6.12
format
var resourceGuids = httpResp.Select(xl => xl.guid).ToList();
var existingBuilds = _DBcontext.Deployedproducts.Where(xl => resourceGuids.Contains(xl.Guid.ToString())).ToList();
var x = existingBuilds.FirstOrDefault(o => o.Guid == item.guid);
Version v = new Version(x.ProductVersion.Substring(0, x.ProductVersion.LastIndexOf("-") + 1).Replace(@"-",""));
if (item.Item1.version < v)
{
x.LatestMajorRelease = item.Item1.version.ToString();
}
Upvotes: 3
Views: 11686
Reputation: 32266
If you can have values without a dash you have to check for that before doing the substring.
string version = x.ProductVersion;
int dashIndex = x.ProductVersion.IndexOf("-");
if(dashIndex > -1)
version = version.Substring(0, dashIndex);
Version v = new Version(version);
Note I used IndexOf
just in case there's a second dash later on.
You could also do other checks like if dashIndex
is 0 then this will result in an empty string as it's likely an invalid version to begin with.
In fact if dashIndex
is less than 3 then it cannot be a valid version (as the version requires at least 2 parts like 1.1 or 2.3).
Upvotes: 3