0

所以我有一个函数调用分类器,它基本上检查目录中的所有文本文件,如果有任何文本文件包含超过 50 行的单词,然后使用其他名为 Text_Classification 的类将该文本文件分类为一种类型,我确信它是正确的并且没有错误。分类后,我需要清理该文本文件并在该文本文件上写一个“行”作为第一个新行(这是其他类,所以不要打扰:))。但是我遇到了一个异常,这意味着该try{}块中有问题。

知道为什么吗?

static void classifer(object state) {
    Console.WriteLine("Time to check if any log need to be classified");
    string[] filename = Directory.GetFiles(@"C:\Users\Visual Studio 2010\Projects\server_test\log");
    foreach(string textfile_name in filename) {
        var lineCount = File.ReadAllLines(textfile_name).Length;
        if(lineCount > 50) {
            Console.WriteLine("Start classifying 1 of the logs");
            Text_Classification classifier = new Text_Classification(textfile_name, 1);
            string type = classifier.passBack_type();  //this function passes back the type of the log(text file)
            Console.WriteLine(type);
            try {
                TextWriter tw = new StreamWriter(textfile_name); //clean the text file
                tw.WriteLine(" ");
                tw.Close();
                TextWriter tw2 = new StreamWriter(textfile_name, true);  //append <Lines> as the first new line on the text file
                tw2.WriteLine("Lines");
                tw2.Close();
            }
            catch {
                Console.WriteLine("cant re-write txt");
            }
        }
    }
}
4

2 回答 2

1

如前所述,这条线是罪魁祸首:

Text_Classification classifier = new Text_Classification(textfile_name, 1);

该类Text_Classification正在打开而不是关闭文件textfile_name

于 2012-05-15T04:22:46.503 回答
0

你可以尝试以下

            File.WriteAllLines(textfile_name, new String[]{" "});
            File.AppendAllLines(textfile_name, new String[]{" Lines "});

代替

               try
                {
                    TextWriter tw = new StreamWriter(textfile_name); //clean the text file
                    tw.WriteLine(" ");
                    tw.Close();


                    TextWriter tw2 = new StreamWriter(textfile_name, true);  //append <Lines> as the first new line on the text file
                    tw2.WriteLine("Lines");
                    tw2.Close();
                }
                catch {
                    Console.WriteLine("cant re-write txt");
                }
于 2012-05-15T04:26:23.353 回答