Ejemplo n.º 1
0
        ///-------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Returns the current contents of a document
        /// </summary>
        ///-------------------------------------------------------------------------------------------------------------
        public string GetDocumentText()
        {
            string            text    = null;
            IVsPersistDocData docData = null;

            try
            {
                // Get or create the buffer
                IVsTextLines buffer = GetRunningDocumentTextBuffer();
                if (buffer == null)
                {
                    docData = CreateDocumentData();
                    buffer  = docData as IVsTextLines;
                }

                // get the text from the buffer
                if (buffer != null)
                {
                    IVsTextStream textStream = buffer as IVsTextStream;
                    if (textStream != null)
                    {
                        int length;
                        int hr = textStream.GetSize(out length);
                        if (ErrorHandler.Succeeded(hr))
                        {
                            if (length > 0)
                            {
                                IntPtr pText = Marshal.AllocCoTaskMem((length + 1) * 2);
                                try
                                {
                                    hr = textStream.GetStream(0, length, pText);
                                    if (ErrorHandler.Succeeded(hr))
                                    {
                                        text = Marshal.PtrToStringUni(pText);
                                    }
                                }
                                finally
                                {
                                    Marshal.FreeCoTaskMem(pText);
                                }
                            }
                            else
                            {
                                text = string.Empty;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (docData != null)
                {
                    docData.Close();
                }
            }

            return(text);
        }