Purpose:在一個測試系統中, 有時候會在特定的目錄中存放測試中的測試資料. 所以便可以在測試時去偵測特定目錄中是否有資料檔案產再去做資料的分析!
Method:
DirectoryInfo dirInfo;
FileSystemWatcher watcher = new FileSystemWatcher();
private void button24_Click(object sender, EventArgs e)
{
button24.BackColor = Color.Green;
button24.Enabled = false;
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.SelectedPath = FileCtrl.CANFilePath;
folderDialog.Description = "Select an listen Folder";
if (folderDialog.ShowDialog() == DialogResult.OK)
{
string selectedPath = folderDialog.SelectedPath;
dirInfo = new DirectoryInfo(selectedPath);
string[] files = Directory.GetFiles(selectedPath);
//設定所要監控的資料夾
watcher.Path = selectedPath;
CommonData.WriteMessage(DateTime.Now.ToString("yyyyMMdd_hhmmss_ffff") + " -- ", "選擇監聽目錄檔案於:" + watcher.Path, Color.Blue, Color.Green);
}
//FileSystemWatcher watcher = new FileSystemWatcher(@"C:\path\to\folder");
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
//watcher.Changed += OnChanged;
watcher.Created += OnCreated;
//watcher.Deleted += OnDeleted;
//watcher.Renamed += OnRenamed;
//watcher.Error += OnError;
if (comboBox_carmodel.Text == "PeakCAN_csv")
{
CommonData.Auto_Detect_Mode = 0;
watcher.Filter = "*.csv";
}
else if (comboBox_carmodel.Text == "CANoe_asc")
{
CommonData.Auto_Detect_Mode = 1;
watcher.Filter = "*.asc";
}
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
button24.BackColor = Color.PeachPuff;
button24.Enabled = true;
}
private void OnCreated(object sender, FileSystemEventArgs e)
{
dirInfo = new DirectoryInfo(e.FullPath.ToString());
CommonData.FilterFlag = true;
Thread.Sleep(100);
CommonData.WriteMessage(DateTime.Now.ToString("yyyyMMdd_hhmmss_ffff") + " -- ", "新建檔案於:" + dirInfo.FullName.Replace(dirInfo.Name, ""), Color.Blue, Color.Green);
CommonData.WriteMessage(DateTime.Now.ToString("yyyyMMdd_hhmmss_ffff") + " -- ", "新建檔案名稱:" + dirInfo.Name, Color.Blue, Color.Green);
CommonData.WriteMessage(DateTime.Now.ToString("yyyyMMdd_hhmmss_ffff") + " -- ", "建立時間:" + dirInfo.CreationTime.ToString(), Color.Blue, Color.Green);
CommonData.WriteMessage(DateTime.Now.ToString("yyyyMMdd_hhmmss_ffff") + " -- ", "目錄下共有:" + dirInfo.Parent.GetFiles().Count() + " 檔案", Color.Blue, Color.Green);
CommonData.WriteMessage(DateTime.Now.ToString("yyyyMMdd_hhmmss_ffff") + " -- ", "目錄下共有:" + dirInfo.Parent.GetDirectories().Count() + " 資料夾", Color.Blue, Color.Green);
}