本人小白菜菜鸟,刚学会c# 不久,用vs2015写了几个程序,大致内容:循环读取文件夹内word信息,
界面两个按钮,开始和停止。点开始后,程序运行,然后界面就卡主不动了,点停止没反应,点窗体上的叉叉也没反应,只能任务管理器结束进程。请问这是为什么?
Ps:代码里面没有timer类的控件。
部分代码如下:
其中的doc和app是全局变量
private static Word.Application app = new Word.Application();
private static Word.Document doc = null;
private void button2_Click(object sender, EventArgs e)
{
var files = Directory.GetFiles(wordPath, "*.doc");
foreach (var file in files)
{
button2.Text = "进行中。。。";
wordName = file.Replace(textBox2.Text, "");
textBox1.Text = wordName;
textBox1.Refresh();
string paperName = wordName.Replace(".doc", "");
if (Sql.existsExam(paperName) > 0) {
listBox2.Items.Add ( "此试卷已存在!"+ file.ToString());
listBox2.Refresh();
continue;
}
try
{
exam_id=Sql.getExamId();
wordNameSave = wordName.Substring(0, wordName.IndexOf("."));
String path = @"d:\word/img_hy/" + exam_id;
BaseClass.createFile(path);
BaseClass.writeFile("d:\\word\\log.txt", "**********************************************************************", 0, 1);
string log = file+" "+ DateTime.Now.ToString();
BaseClass.writeFile("d:\\word\\log.txt",log, 0, 1);
doc = app.Documents.Open(file); //一会要记录word打开的文档
string strContent = ReadWordMian.readWordMain(app, doc, path, wordNameSave);
Sql.insertExam(ReadWordMian.paperHead,exam_id, grade_id, subject_id);
cutExercises(strContent);
log = "we have a finish ! " + wordNameSave + " " + DateTime.Now.ToString();
//Console.WriteLine(DateTime.Now.ToString());
BaseClass.writeFile("d:\\word\\log.txt", log, 0, 1);
}
catch (Exception err) {
button2.Text = "批量入库";
//listBox2.Items.Add("异常:"+"此文件读取异常"+ file+" "+err);
BaseClass.writeFile("d:\\word\\log.txt", "异常:" + "此文件读取异常" + file + " " + err, 0, 1);
}
}
// listBox2.Items.Add(error_string);
doc.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
button2.Text = "批量入库";
}