using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Threading; namespace TxtToDB { public partial class frmMain : Form { Db db = new Db(); public frmMain() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void btnSelectSourceDir_Click(object sender, EventArgs e) { folderBrowser.ShowDialog(); txtSourceDir.Text = folderBrowser.SelectedPath; } private void btnExecute_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtConn.Text.Trim())) { MessageBox.Show(null, "请填写数据库连接字符串!", "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrEmpty(txtTable.Text.Trim())) { MessageBox.Show(null, "请填写数据表名称!", "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((string.IsNullOrEmpty(txtSource.Text.Trim())) || (string.IsNullOrEmpty(txtCaseNumber.Text.Trim())) || (string.IsNullOrEmpty(txtContent.Text.Trim()))) { MessageBox.Show(null, "请填写所有字段!", "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrEmpty(txtSourceDir.Text.Trim())) { MessageBox.Show(null, "请选择文本目录!", "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Thread th = new Thread(new ThreadStart(Execute)); th.Start(); } private void Execute() { string[] soursetxt = Directory.GetFiles(txtSourceDir.Text.Trim(), "*.txt"); btnExecute.Enabled = false; int i = 1; lblTotal.Text = "总计:" + soursetxt.Length.ToString(); string filename = ""; string strCreateTable = @"IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[{0}]') AND type in (N'U')) BEGIN CREATE TABLE [{0}]( [{1}] nvarchar(256) NULL, [{2}] nvarchar(200) NULL, [{3}] nvarchar(max) null) END"; strCreateTable = string.Format(strCreateTable, txtTable.Text.Trim(), txtSource.Text.Trim(), txtCaseNumber.Text.Trim(), txtContent.Text.Trim()); int result = db.ExeSql(txtConn.Text.Trim(), strCreateTable); foreach (string txt in soursetxt) { if (!string.IsNullOrEmpty(txt)) { try { filename = txt.Replace(txtSourceDir.Text.Trim(), "").Replace("//", ""); string[] args = filename.Replace(".txt", "").Split('_'); string strSource = @"http://www.gzcourt.org.cn/showCpws?" + args[1] + "=" + args[2] + "=" + args[3]; string strCaseNumber = args[0]; string strContent = GetStringFileContent(txt, "gb2312"); string strSql = "insert into [" + txtTable.Text.Trim() + "]([" + txtSource.Text.Trim() + "],[" + txtCaseNumber.Text.Trim() + "],[" + txtContent.Text.Trim() + "])"; strSql += "values(N'" + strSource.Replace("'", "''") + "',N'" + strCaseNumber.Replace("'", "''") + "',N'" + strContent.Replace("'", "''") + "')"; int insert = db.ExeSql(txtConn.Text.Trim(), strSql); } catch { AppendTextToFile(AppDomain.CurrentDomain.BaseDirectory + "error.log", txt + "/r/n"); continue; } lblCompleted.Text = "已处理:" + i.ToString(); i = i + 1; } } MessageBox.Show(null, "处理完成!", "处理完成", MessageBoxButtons.OK, MessageBoxIcon.Information); btnExecute.Enabled = true; } /// <summary> /// 将文本字符窜追加的文件末尾,成功返回true /// </summary> /// <param name="FilePaths">存在的文件路径</param> /// <param name="AppendText">要追加的文本</param> /// <returns></returns> private static bool AppendTextToFile(string FilePaths, string AppendText) { StreamWriter sw = null; FileStream fstream = null; bool returnvalue = false; try { if (!File.Exists(FilePaths)) CreateFile(FilePaths); fstream = new FileStream(FilePaths, FileMode.Append, FileAccess.Write); sw = new StreamWriter(fstream); sw.Write(AppendText); sw.Close(); fstream.Close(); returnvalue = true; } catch (Exception ex) { throw ex; } finally { if (sw != null) sw.Close(); if (fstream != null) fstream.Close(); if (sw != null) sw.Close(); } return returnvalue; } /// <summary> /// 根据文件创建空文件,成功返回true /// </summary> /// <param name="FilePaths">存在的文件路径</param> /// <returns></returns> private static bool CreateFile(string FilePaths) { FileStream fstream = null; StreamWriter sw = null; string content = null; bool returnvalue = false; try { string folder = System.IO.Path.GetDirectoryName(FilePaths); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); fstream = new FileStream(FilePaths, FileMode.OpenOrCreate, FileAccess.ReadWrite); sw = new StreamWriter(fstream); sw.Write(content); sw.Close(); fstream.Close(); returnvalue = true; } catch (Exception ex) { throw ex; } finally { if (sw != null) sw.Close(); if (fstream != null) fstream.Close(); } return returnvalue; } /// <summary> /// 根据文件名称和编码格式,获取该文件的字符窜 /// </summary> /// <param name="FilePaths">文件全路径</param> /// <param name="encodestr">字符编码类型</param> /// <returns></returns> private static string GetStringFileContent(string FilePaths, String encodestr) { string result = null; FileStream Fs = null; StreamReader sr = null; try { Fs = new FileStream(FilePaths, FileMode.Open, FileAccess.Read); Encoding encode = System.Text.Encoding.GetEncoding(encodestr); sr = new StreamReader(Fs, encode); Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); while (count > 0) { String str = new String(read, 0, count); result += str; count = sr.Read(read, 0, count); } sr.Close(); Fs.Close(); } catch (Exception ex) { throw ex; } finally { if (sr != null) sr.Close(); if (Fs != null) Fs.Close(); } return result; } private void frmMain_FormClosed(object sender, FormClosedEventArgs e) { Application.ExitThread(); } } }