C#監控判斷檔案有無內容,有內容則讀取寫入資料庫
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.IO; using System.Data.SqlClient; using System.Threading; using System.Data;
class Program { static void Main(string[] args) {
//迴圈讀取TXT文件 while (true) { //Console.Write("請輸入指定的檔案路徑(請拖拽檔案到此處):"); //string path = Console.ReadLine(); PrintFileVersionInfo(@"\\192.168.0.15\CadPrint\FactoryNumber.txt"); }
}
/// <summary> /// 列印指定檔案的詳細資訊 /// </summary> /// <param name="path">指定檔案的路徑</param> static void PrintFileVersionInfo(string path) { FileInfo fileInfo = null; try { fileInfo = new FileInfo(path); } catch (Exception e) { Console.WriteLine(e.Message); // 其他處理異常的程式碼 } // 如果檔案存在 if (fileInfo != null && fileInfo.Exists) { //計算文本里有無內容,無為0,有為1 FileVersionInfo info = FileVersionInfo.GetVersionInfo(path); int fileLen = Convert.ToInt16(Math.Ceiling(fileInfo.Length / 1024.0)); //判斷檔案有無內容,有內容執行儲存過程 if (fileLen>0) { //執行SQL程式碼或儲存過程 SqlConnection sqlConnection = new SqlConnection("server=192.168.0.15;uid=sa;pwd=sa;database=資料庫"); SqlCommand sqlCommand = new SqlCommand("儲存過程名稱", sqlConnection); sqlCommand.CommandType = CommandType.StoredProcedure; sqlConnection.Open(); sqlCommand.ExecuteNonQuery(); Console.Write("時間:" + DateTime.Now + ",標記文字資料匯入到資料庫中。。。。。"); Thread.Sleep(6000); sqlConnection.Close();
//清空文字檔案裡的內容 File.WriteAllText(path, string.Empty);
} else { Console.Write("時間:" + DateTime.Now + ",標記文字無內容"); Thread.Sleep(6000); } } else { Console.WriteLine("時間:" + DateTime.Now + ",標記文字檔案路徑不存在"); File.WriteAllText(path,string.Empty); Thread.Sleep(500); } // 末尾空一行 Console.WriteLine(); }
}