In this post, we will learn how to handle string operations for common methods.
When I planned to migrate the VB6 products to .NET technologies, I thought VB.NET is a better choice since it has the similarity of VB6 and it has most predefined functionalities.
I have the knowledge of Visual Basic 6 and wished to learn a new language so I preferred C# .NET. But I faced a lot of problems to find the functionalities equivalent to VB6 while migrating to C# Winforms. Finally, after a lot of research, I got the solution, that is shared below with you.
Here, I have included the methods for String operations of Left, Right, Mid, and Instring.
Find the below code for the Right string.
- public static string strRight(string strValue, int intLength)
- {
- string strRet = string.Empty;
- try
- {
- strRet = strValue.Substring(strValue.Length - intLength);
- }
- catch (Exception ex)
- {
- strRet = strValue;
- }
- return strRet;
- }
Find the below code for the Left string.
- public static string strLeft(string strValue, int intLength)
- {
- string strRet = string.Empty;
- try
- {
- if (string.IsNullOrEmpty(strValue)) strRet = strValue;
- intLength = Math.Abs(intLength);
- strRet = strValue.Length <= intLength ? strValue : strValue.Substring(0, intLength);
- }
- catch (Exception ex)
- {
- strRet = strValue;
- }
- return strRet;
- }
Find the below code for the Middle string.
- public static string strMid(string strValue, int intStartPos, int intCharCnt)
- {
- string strRet = string.Empty;
- try
- {
- strRet = strValue.Substring(intStartPos - 1, intCharCnt);
- }
- catch (Exception ex)
- {
- strRet = strValue;
- }
- return strRet;
- }
Find the below code for finding the particular character position in a given string.
- private int instr(int StartPos, String SearchString, char chrInput, int IgnoreCaseFlag)
- {
- int result = 1;
- if (IgnoreCaseFlag == 1)
- {
- result = SearchString.IndexOf(chrInput.ToString(), StartPos, StringComparison.OrdinalIgnoreCase);
- }
- else
- result = SearchString.IndexOf(chrInput.ToString(), StartPos);
- return result;
- }
You can write these above procedures in class files and use them all over your project .
Note
The other way of getting these functionalities without writing these methods include references of Microsoft.VisualBasic in your project and include "using Microsoft.VisualBasic;" this line in your .cs file where you want to use VB6 equivalent functionalities and follow below codes,
- For Left ---> Strings.Left("VisualBasic', 2)
- For Right ---> Strings.Right("VisualBasic', 2)
- For Mid ---> Strings.Mid("VisualBasic',7, 5)
- For Instring --> Strings.InStr(1, "Visual/Basic", "/")