Exemplo n.º 1
0
        public static string ToTitle(string src, string locale)
        {
            if (src == null)
            {
                return(string.Empty);
            }

            int    length = src.Length + 10;
            IntPtr resPtr = Marshal.AllocCoTaskMem(length * 2);

            try
            {
                ErrorCode err;
                int       outLength = NativeMethods.u_strToTitle(resPtr, length, src, src.Length, IntPtr.Zero, locale, out err);
                if (err > 0 && err != ErrorCode.BUFFER_OVERFLOW_ERROR)
                {
                    throw new Exception("UnicodeString.ToTitle() failed with code " + err);
                }
                if (outLength > length)
                {
                    err = ErrorCode.NoErrors;                     // ignore possible U_BUFFER_OVERFLOW_ERROR
                    Marshal.FreeCoTaskMem(resPtr);
                    length = outLength + 1;
                    resPtr = Marshal.AllocCoTaskMem(length * 2);
                    NativeMethods.u_strToTitle(resPtr, length, src, src.Length, IntPtr.Zero, locale, out err);
                }
                if (err > 0)
                {
                    throw new Exception("UnicodeString.ToTitle() failed with code " + err);
                }

                string result = Marshal.PtrToStringUni(resPtr);
                if (result != null)
                {
                    // Strip any garbage left over at the end of the string.
                    if (err == ErrorCode.STRING_NOT_TERMINATED_WARNING)
                    {
                        result = result.Substring(0, outLength);
                    }
                }
                return(result);
            }
            finally
            {
                Marshal.FreeCoTaskMem(resPtr);
            }
        }