using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace 源代码修改
{
public class ReadDocument : IOperateDocument
{
private FileInfo documentFileInfo;
private StreamReader reader;
// 以原语言为键,翻译后的语言为值
private Dictionary<string, string> stringTable;
private bool hasFoundDocument;
public bool HasFoundDocument
{
get
{
return hasFoundDocument;
}
}
private bool documentFormatIsOK;
public bool DocumentFormatIsOK
{
get
{
return documentFormatIsOK;
}
}
private string GetKey(ref string aLine)
{
// 跳过分隔符内的说明用的数据
int i = 0;
int countOfHasFoundSeparator = 0 ;
for (; i != aLine.Length; ++i)
{
if (aLine[i] == SeparatorBetweenTwoAreas)
{
++countOfHasFoundSeparator;
if (countOfHasFoundSeparator == AmountOfSepator)
{
++i;
break;
}
}
}
if (i >= aLine.Length)
{
// 读取键失败
return null;
}
string key = null;
for (; i != aLine.Length && aLine[i] != SeparatingString[0]; ++i)
key += aLine[i];
string newALine = null;
for (; i != aLine.Length; ++i)
newALine += aLine[i];
aLine = newALine;
return key;
}
private string GetValue(string aLine)
{
if (aLine == null)
return null;
if (aLine.Length <= SeparatingString.Length)
return null;
for (int i = 0; i != SeparatingString.Length; ++i)
{
if (aLine[i] != SeparatingString[i])
return null;
}
string value = null;
for (int i = SeparatingString.Length; i != aLine.Length; ++i)
value += aLine[i];
return value;
}
// 将翻译后的文档读入查找表中
private void ReadStringToTable()
{
string aLine = reader.ReadLine();
if (aLine == null)
{
documentFormatIsOK = false;
return;
}
while (aLine != null)
{
string originalString = GetKey(ref aLine);
if (originalString == null)
{
documentFormatIsOK = false;
return;
}
if (!stringTable.ContainsKey(originalString))
{
string targetString = GetValue(aLine);
if (targetString == null)
{
documentFormatIsOK = false;
stringTable.Clear();
return;
}
stringTable[originalString] = targetString;
aLine = reader.ReadLine();
}
else
{
// 出现了重复待修改的代码
documentFormatIsOK = false;
return;
}
}
documentFormatIsOK = true;
}
public ReadDocument()
{
documentFileInfo = new FileInfo(DocumentName);
try
{
reader = documentFileInfo.OpenText();
}
catch (FileNotFoundException)
{
// 没有找到DocumentName文件.
hasFoundDocument = false;
return;
}
hasFoundDocument = true;
stringTable = new Dictionary<string, string>();
ReadStringToTable();
}
public bool ContainsOriginalString(string originalString)
{
return stringTable.ContainsKey(originalString);
}
public string GetTargetString(string originalString)
{
return stringTable[originalString];
}
public void OverReading()
{
if (reader != null)
reader.Close();
}
public void CreateANewDocument()
{
StreamWriter writer = new StreamWriter(documentFileInfo.FullName, false, Encoding.UTF8);
writer.Close();
reader = documentFileInfo.OpenText();
}
}
}