Вот пример 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 다, add the appropriate ending.
</p><p>먹다 - 먹 + 어요 = 먹어요 <br />
마시다 - 마시 + 어요 - 마시어요 - 마셔요. <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;
}
}