Hello,
I’m looking for the best way to do approach an issue I’ve run into. I’m creating a flat file with a fixed width for each column of 50 characters. Strings from my datatable that are less than 50 have PadRight(50) applied to them so that each column is 50 characters long.
My issue is that I want to prevent columns from going over 50 characters. If one of the strings is, say 55 characters, it just overflows and ruins the row, preventing the file from being loaded successfully. My ideal solution would be to just take the first 50 characters of the 55 character string and discard the rest.
Thank you for any help/guidance you can provide.
If you’re only interested in cutting off excess characters, have you looked at String.Substring(int, int)?
https://docs.microsoft.com/en-us/dotnet/api/system.string.substring?view=net-5.0#System_String_Substring_System_Int32_System_Int32_
myString.PadRight(50).Substring(0,50) ?
Easy enough to wrap into a helper class or extension method as well
I don’t understand what you’re asking.
Do you mean you want to write code that doesn’t write a line longer than or shorter than 50 characters? Do you mean you don’t trust the file, and you want to make sure the lines you read are never a different length than 50?
Either way, write a method to do it for you and pass any string through this method first:
If one of the strings is, say 55 characters, it just overflows and ruins the row, preventing the file from being loaded successfully. My ideal solution would be to just take the first 50 characters of the 55 character string and discard the rest.
I’d be very careful here; there are not many cases where arbitrary truncation is useful. In my experience it is 99.9% of time a mistake that’ll cause a domino effect of problems downstream.
If this is for production code and not just learning, I’ve had success using FlatFiles before, which can enforce this sort of thing for you.
What you need is a Left Function, Visual Basic and othe languages used to have it, it basically cuts the string x characters to the left… unfortunately CSharp doensn’t have it, but there are several ways to do it, here is a sample, you might need to work it out a bit:
public static class StringExtensions
{
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return (value.Length <= maxLength
? value
: value.Substring(0, maxLength)
);
}
}