以前我是會很笨地用List記住資料夾內的檔案,然後每幾秒便用For迴圈去比對檢查,現在有空去研究,便發現了王道方法,輕鬆且簡單。
C#有FileSystemWatcher這個Library,專門用來監視資料夾檔案狀態,因此簡單地設定和啟用,便可為程式去監聽指定的資料夾內檔案狀態。
- using System.Collections;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.IO;
- public class XXX : MonoBehaviour {
- private FileSystemWatcher fileSystemWatcher;
- void Start ()
- {
- DetectFileAction();
- }
- void Update ()
- {
- }
- public void DetectFileAction()
- {
- fileSystemWatcher = new FileSystemWatcher("S:/Data/", "*.txt");
- fileSystemWatcher.Created += OnChanged;
- fileSystemWatcher.Renamed += OnChanged;
- fileSystemWatcher.Changed += OnChanged;
- fileSystemWatcher.Deleted += OnChanged;
- fileSystemWatcher.EnableRaisingEvents = true;
- }
- void OnChanged(object source, FileSystemEventArgs e)
- {
- Debug.Log("有檔案被" + e.ChangeType + " = " + e.FullPath);
- }
- }
可以看到我偵測四種狀態:創造檔案、重新命名檔案、改變檔案的內容和刪除檔案。
fileSystemWatcher.EnableRaisingEvents是指啟動此程序的意思。
由上而下分別是創造檔案、重新命名檔案、改變檔案的內容和刪除檔案時所出現的相對應訊息,這邊特地列出是為了表明有些時候做某個動作,所得到的回饋會不只一個。
最後有一個很重要的是,如果是較大的檔案,最好不要接收到訊息便立即拿來使用。例如我用Web攝影機錄製了一段使用者的影像,並且將影片儲存到某個資料夾內;雖然其他的程式會立刻接收到Created的訊息,但是檔案實際上可能還沒有創建完成,所以若立即取得並播放的話很可能是白色畫面,因此我都會等一兩秒後再來處理。
沒有留言:
張貼留言