что за ошибка в обработке этой строки c #? - PullRequest
1 голос
/ 13 ноября 2009

Вот пример HTML-документа, который я передаю как MemoryStream в коде, как показано ниже

<h5>Sample Document </h5>
<h3> Present Tense </h3>

</p><p>The present tense is just as you have learned.  You take the dictionary form of a verb, drop the &#45796;, add the appropriate ending.

</p><p>&#47673;&#45796; - &#47673; + &#50612;&#50836; = &#47673;&#50612;&#50836; <br />
&#47560;&#49884;&#45796; - &#47560;&#49884; + &#50612;&#50836; - &#47560;&#49884;&#50612;&#50836; - &#47560;&#49492;&#50836;. <br />

</p><p>This tense is used to represent what happens in the present.  I eat. I drink.  It is a general term for the present. 

Упомянутая ниже программа содержит три функции

  • Main
  • ReadDocument
  • TestByteOffSet

Основная функция принимает указанный выше HTML-документ, преобразуя его в memoryStream, а затем передает его в функцию ReadDocument, которая сохраняет результат в переменной с именем docContent. Это переменная уровня класса.

Затем основная функция берет выделенный текст, используя myRange.Text пытается найти его индекс в данном документе. Как только индекс найден, он сохраняется в переменной intByteOffSet.

Теперь Третья функция TestByteOffSet пытается убедиться, что индекс, сохраненный в intByteOffSet, верен или нет.

Здесь возникают проблемы, когда я пытаюсь получить строку из byteOffSet, я не получаю выделенный текст.

Исходный код

using System;
using System.Collections.Generic;
using System.Text;

namespace MultiByteStringHandling
{
    class Program
    {

        static void Main(string[] args)
        {
            FileStream fs = new FileStream(FileName, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            byte[] bit = br.ReadBytes((int)fs.Length);
            MemoryStream Mr = new MemoryStream(bit);
            ReadDocument(Mr);

            mshtml.IHTMLTxtRange CompleteRange = 
                              _body.createTextRange().duplicate();
            int intByteOffset = 0;
            Regex reg = default(Regex);

            try
            {
                // Get all of the text that is in between HTML tags. 
                string regSearchText = myRange.htmlText;
                string strTemp = regSearchText + "\\s*";

                string strExp = ">(([^<])*?)" + strTemp + "(([^<])*?)<";
                string _cleanedSource = "";

                _cleanedSource = CompleteRange.htmlText;

                // Use regular expressions to find a collection of matches 
                //that match a certain pattern. 
                foreach (Match m in Regex.Matches(_cleanedSource, strExp,
                       RegexOptions.IgnoreCase))
                {
                    Int32 ret = default(Int32);
                    Int32 index = default(Int32);
                    string strMatch = m.Value;

                    foreach (Match m2 in Regex.Matches(strMatch, strTemp, 
                            RegexOptions.IgnoreCase))
                    {
                        // Increment counter when finding a match. 
                        intCount += 1;
                        // If counter matches occurrence number, return 
                        //source offset. 
                        if (intCount == OccurenceNo)
                        {
                            //Source offset is the index of the overall 
                            //match + index innerText Match. 

                            int intCharOffset = m.Index + m2.Index;
                            System.Text.UTF8Encoding d = new        
                                        System.Text.UTF8Encoding();
                            // Using the SourceText will give an accurate 
                            //byte offset. 
                           intByteOffset = d.GetBytes(
                          _cleanedSource.Substring(0, intCharOffset)).Length;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
             throw ex;
            }
            finally
            {

            }
        }

    private void ReadDocument(Stream sD)
    {
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms);
        bool hasMore = true;
        sD.Position = 0;
        using (System.IO.BinaryReader br = new System.IO.BinaryReader(sD))
        {
            while (hasMore)
            {
                byte[] buffer = br.ReadBytes(8192);
                hasMore = buffer.Length > 0;
                if (hasMore)
                {
                    bw.Write(buffer);
                }
            }
        }
        byte[] docBuffer = ms.GetBuffer();
        docContent = new byte[docBuffer.Length + 1];
        Array.Copy(docBuffer, docContent, docBuffer.Length);
    }
    private bool TestByteOffset(TransparencyItemType transparency)
    {
        System.Text.UTF8Encoding encoding = default(System.Text.UTF8Encoding);
        string byteOffsetLabel = null;
        Int32 iLength = default(Int32);
        Int32 offset = default(Int32);

        if (((transparency.Label == null) == false))
        {
            iLength = Convert.ToInt32(transparency.Label.IEOffset.Length);
            offset = Convert.ToInt32(transparency.Label.IEOffset.Offset);
        }
        else if (((transparency.Value == null) == false))
        {
            if(transparency.Value.ByteOffset!=null)
            {
                if (transparency.Value.ByteOffset.Offset != -1)
                {
                    iLength = Convert.ToInt32(transparency.Value.ByteOffset.Length);
                    offset = Convert.ToInt32(transparency.Value.ByteOffset.Offset);
                }
            }
        }
        else
        {
            return false;
        }
  }

1 Ответ

0 голосов
/ 24 ноября 2009

Источник, который размещен, не является полным. TestByteOffset никогда не вызывается. FileName, mshtml, _body, myRange, intCount и OccurenceNo не определены. На docContent никогда не ссылаются в Main, равно как и на любую другую переменную, которая может содержать исходный текст (fs, br, bit или Mr). Кажется, что CompleteRange должен содержать текст, но он не может получить его, если _body не может предоставить его, а _body не определено.

Пожалуйста, убедитесь, что код, который вы публикуете, является полным и может быть скомпилирован.

Было бы намного проще отлаживать код, если бы в нем не было столько ненужных манипуляций (как упоминал Фредрик Мёрк). Дело не только в правильном использовании; если код сложен для понимания, его гораздо сложнее отладить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...