フォルダーを監視するコードを C# で書いています。ファイルが作成されると、コードはいくつかのアクションを実行し、結果をログ ファイルに書き込みます。私はこの非常に奇妙な行動をとっています。i ファイルが監視フォルダーに作成されると、変更を処理する関数が 2 回実行されます。たとえそれが 1 つの変更イベントであっても。最初は FileSystemWatcher を使用しました。しかし、私はそれを調べた後、多くの安定性が発行されていることがわかったので、はるかに安定した暗示である MyFileSystemWatcher に切り替えました。しかし、ログファイルにはまだ重複があります。変更を検索するための変更中のコードが 2 回実行される理由がわかりません。ここにコードサンプルがあります
protected void Folder_Watch(string path)
{
if (!Directory.Exists(path))
{
try
{
System.IO.Directory.CreateDirectory(path);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error: " + ex.Message.ToString() + Environment.NewLine);
}
}
MyFileSystemWatcher m_Watcher = new MyFileSystemWatcher(path);
//m_Watcher.Path = path;
m_Watcher.Filter = "*.*";
m_Watcher.NotifyFilter = NotifyFilters.FileName;
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.EnableRaisingEvents = true;
}
ここに onChange 関数があります
private void OnChanged(object source, FileSystemEventArgs e)
{
File.AppendAllText(logPath + "\\SSHConnectionLog.log", "[]*******" + DateTime.Now + " OnChanged function: " + Environment.NewLine);
// Decrypt the file.
DecryptFile(keyPath + "\\id_rsa_Encrypted", keyPath + "\\id_rsa", sSecretKey);
// Remove the Key from memory.
//PKey = new PrivateKeyFile(keyPath + "\\id_rsa");
keyResult.Text = "RSA keys Were Generated at:" + keyPath;
//ScpClient client = new ScpClient("remnux", "adi", PKey);
Chilkat.SFtp client = new Chilkat.SFtp();
string[] tempPath = e.FullPath.Split('\\');
string fullPathNew = string.Empty;
for (int i = 0; i < tempPath.Length - 1; i++)
{
fullPathNew += tempPath[i];
}
if (Directory.Exists(fullPathNew))
{
sshConnect(client);
File_Upload(e.FullPath, client);
}
else
{
try
{
sshConnect(client);
System.IO.Directory.CreateDirectory(fullPathNew);
File_Upload(e.FullPath, client);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error in OnChanged function: " + ex.Message.ToString() + Environment.NewLine);
}
}
}
どんな助けでも非常に感謝します!