我正在开发各种各样的Chat-Bot,我正在尝试使用'学习'功能进行编码。我对编码很新,但我怀疑我的问题与我没有关闭读取流但我不知道怎么做。我想帮助找到解决这个难题的最有效方法。这是我的代码。
class Program
{
static bool isRecording = false;
static bool isTraining = false;
static bool shutdown = false;
static string path = Path.Combine(Directory.GetCurrentDirectory(), "memory.txt");
static string inputValue;
static string outputValue = " ";
static void Main(string[] args)
{
Console.WriteLine("Computer: Hello! I am MyAI Version 2.0.");
Console.WriteLine("Training?");
inputValue = Console.ReadLine();
inputValue = inputValue.ToLower();
inputValue = inputValue.Trim(new Char[] { ' ', '.', ',', ':', ';', '*' });
if (inputValue == "yes")
{
isTraining = true;
Console.WriteLine("Training mode set to true.");
Console.ReadLine();
}
else
{
isTraining = false;
Console.WriteLine("Training mode set to false");
Console.ReadLine();
}
Console.Clear();
CollectInput();
}
static void CollectInput()
{
var lines = System.IO.File.ReadLines(path);
while (!shutdown)
{
Console.Write("User: ");
inputValue = Console.ReadLine();
inputValue = inputValue.ToLower();
inputValue = inputValue.Trim(new Char[] { ' ', '.', ',', ':', ';', '*' });
StringComparison comp = StringComparison.OrdinalIgnoreCase;
if (inputValue == "hi" || inputValue == "hello" || inputValue == "greetings")
{
outputValue = "hi";
}
else if (inputValue.Contains("how are you"))
{
outputValue = "good";
}
else
{
if (isTraining)
{
if (isRecording)
{
//This is where I would like to write inputValue to path
isRecording = false;
}
}
if (File.ReadAllLines(path).Contains(inputValue))
{
outputValue = File.ReadLines(path)
.SkipWhile(line => line != inputValue)
.Skip(1)
.FirstOrDefault();
}
else
{
if (inputValue.Contains("?"))
{
outputValue = inputValue;
//This is where I would like to write inputValue to path
isRecording = true;
}
else
{
outputValue = "what about it?";
}
}
}
Console.Write("Computer: ");
Console.WriteLine(outputValue);
outputValue = " ";
}
}
}
答案 0 :(得分:0)
而不是使用File.ReadLines
,File.Open
文件一次,然后使用相同的句柄读/写它。
答案 1 :(得分:0)
根据MSDN,https://msdn.microsoft.com/en-us/library/dd383503(v=vs.110).aspx,File.ReadLines允许您在完全读取之前开始枚举文件的行。对我说的是,在您的枚举开始后,该文件可能会在一段时间内保持打开状态。
如果您不需要该异步行为,只需切换到File.ReadAllLines即可。您可以类似地迭代它们,您应该能够使用File.AppendAllLines写入该文件。