本文整理汇总了C#中System.IO.FileSystemWatcher.WaitForChanged方法的典型用法代码示例。如果您正苦于以下问题:C# FileSystemWatcher.WaitForChanged方法的具体用法?C# FileSystemWatcher.WaitForChanged怎么用?C# FileSystemWatcher.WaitForChanged使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileSystemWatcher
的用法示例。
在下文中一共展示了FileSystemWatcher.WaitForChanged方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
if (args.Length != 2)
{
PrintUsage();
return;
}
string filepath = args[0];
int waitTime = Convert.ToInt32(args[1]);
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = filepath;
watcher.Filter = "";
watcher.IncludeSubdirectories = true;
WaitForChangedResult result;
do
{
result = watcher.WaitForChanged(WatcherChangeTypes.All,
waitTime);
} while (!result.TimedOut);
Console.WriteLine("timedout!");
}
示例2: ReadFromFile
private static void ReadFromFile()
{
long offset = 0;
FileSystemWatcher fsw = new FileSystemWatcher
{
Path = "C:\\Share\\1",
Filter = "INDICATE_REPORT.txt"
};
FileStream file = File.Open(
FilePathWip21,
FileMode.Open,
FileAccess.Read,
FileShare.Write);
StreamReader reader = new StreamReader(file);
while (true)
{
fsw.WaitForChanged(WatcherChangeTypes.Changed);
file.Seek(offset, SeekOrigin.Begin);
if (!reader.EndOfStream)
{
do
{
Console.WriteLine(reader.ReadLine());
} while (!reader.EndOfStream);
offset = file.Position;
}
}
}
示例3: AutoIndexButton_Click
private void AutoIndexButton_Click(object sender, RoutedEventArgs e)
{
var worker = new BackgroundWorker();
worker.DoWork += (s, args) =>
{
var ps = args.Argument as string[];
FileSystemWatcher watcher = new FileSystemWatcher(ps[0], ps[1])
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite
};
while (true)
{
var results = watcher.WaitForChanged(WatcherChangeTypes.All, 1000);
if (!results.TimedOut)
{
System.Diagnostics.Debug.WriteLine("watcher.WaitForChanged({0}): {1} -> {2}", results.ChangeType, results.OldName, results.Name);
this.Dispatcher.Invoke((Action)(() =>
{
RebuildIndex();
searchButton.Background = Brushes.Pink;
}));
}
}
};
worker.RunWorkerAsync(new[] {folderPathTextBox.Text, filePatternTextBox.Text});
}
示例4: Mensagens
/// <summary>
/// Espera por novas mensagens e retorna para a View
/// </summary>
/// <param name="chat"></param>
/// <param name="ignoreListener"></param>
/// <returns></returns>
public ActionResult Mensagens(string id, bool ignoreListener)
{
if (!string.IsNullOrEmpty(id))
{
if (ignoreListener == false)
{
FileSystemWatcher watcher = new FileSystemWatcher(MvcApplication.FolderLog);
watcher.Filter = id + ".xml";
watcher.EnableRaisingEvents = true;
if (watcher.WaitForChanged(WatcherChangeTypes.Changed, 60000).ChangeType == WatcherChangeTypes.Changed) { }
}
return new ConversaController().Mensagens(id);
}
return null;
}
示例5: Main
static void Main(string[] args)
{
objXmlDocumentDataBase = new XmlDocument();
// Create watcher and set point to C:\synchronyze
FileSystemWatcher watcher = new FileSystemWatcher(FILE_PATH);
watcher.NotifyFilter = NotifyFilters.LastWrite;
// Mapping events
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.WaitForChanged(WatcherChangeTypes.Changed);
// -- Pause
Console.ReadKey();
}
示例6: WaitForChanged
/// <summary>
/// This method is to be used for win98,winME
/// </summary>
/// <param name="directoryPath"></param>
/// <param name="filter"></param>
/// <param name="watcherChangeTypes"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public WaitForChangedResult WaitForChanged(string directoryPath, string filter,
WatcherChangeTypes watcherChangeTypes,
int timeOut) {
if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
var watcher = new FileSystemWatcher(directoryPath, filter);
WaitForChangedResult waitForChanged = watcher.WaitForChanged(watcherChangeTypes, timeOut);
return waitForChanged;
}
waitForChangedDelegate d = waitForChangedHandler;
IAsyncResult res = d.BeginInvoke(directoryPath, filter, watcherChangeTypes, timeOut, null, null);
if (res.IsCompleted == false)
res.AsyncWaitHandle.WaitOne(timeOut, false);
return res.IsCompleted ? d.EndInvoke(res) : new WaitForChangedResult();
}
示例7: Main
static void Main(string[] args)
{
var fw = new FileSystemWatcher(@"C:\temp\T1Watcher\", "*.txt");
while (true)
{
Console.WriteLine("added file {0}",
fw.WaitForChanged(WatcherChangeTypes.All).Name);
}
//System.IO.FileSystemWatcher watcher;
//watcher = new System.IO.FileSystemWatcher();
//watcher.Path = @"C:\temp\T1Watcher\";
//watcher.EnableRaisingEvents = true;
//watcher.Filter = "*.txt";
//watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
//watcher.Changed += new System.IO.FileSystemEventHandler(FileChanged);
}
示例8: Chamadas
/// <summary>
/// Espera pela criação de uma nova chamada
/// </summary>
/// <returns></returns>
public bool Chamadas()
{
try
{
FileSystemWatcher watcher = new FileSystemWatcher(MvcApplication.FolderLog);
watcher.EnableRaisingEvents = true;
if (watcher.WaitForChanged(WatcherChangeTypes.Created, MvcApplication.DelayListener).ChangeType == WatcherChangeTypes.Created)
return true;
else
return false;
}
catch
{
return false;
}
}
示例9: Watch
public void Watch(string fileToTail)
{
this.fileToTail = fileToTail;
try
{
if (!File.Exists(fileToTail))
{
throw new FileNotFoundException("Could not find the file", fileToTail);
}
var directory = Path.GetDirectoryName(fileToTail);
// Dispose previous instance to reduce memory usage
if (fileSystemWatcher != null)
{
fileSystemWatcher.Dispose();
fileSystemWatcher = null;
}
fileSystemWatcher = new FileSystemWatcher(directory) { Filter = fileToTail };
fileSystemWatcher.Filter = "*.*";
fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite;
fileSystemWatcher.Changed += Fsw_Changed;
fileSystemWatcher.EnableRaisingEvents = true;
fileSystemWatcher.InternalBufferSize = 1024 * 1024 * 2;
serialFileReader.Enqueue(fileToTail);
while (true)
{
fileSystemWatcher.WaitForChanged(WatcherChangeTypes.Changed);
}
}
catch (Exception ex)
{
exceptionHandler(ex);
}
}
示例10: ChamadaIniciada
/// <summary>
/// Verifica se a chamada não está mais no status de aguardando
/// </summary>
/// <param name="id">identificador da conversa</param>
/// <returns></returns>
public bool ChamadaIniciada(string id)
{
try
{
FileSystemWatcher watcher = new FileSystemWatcher(MvcApplication.FolderLog);
watcher.Filter = id + ".xml";
watcher.EnableRaisingEvents = true;
if (watcher.WaitForChanged(WatcherChangeTypes.Changed, 60000).ChangeType == WatcherChangeTypes.Changed)
{
var conversa = new Conversa(Conversa.ObterCaminhoArquivo(id));
if (conversa.Estado != EstadoConversa.EmEspera)
return true;
}
return false;
}
catch (Exception ex)
{
throw ex;
}
}
示例11: StartMonitoring
public void StartMonitoring()
{
// Get the callback channel to the client that invoked StartMonitoring
var callback = OperationContext.Current.GetCallbackChannel<IBarnCallback>();
StreamEnabled = true;
Console.WriteLine("Starting stream...");
// Create a file system watcher that notifies us whenever the file is being changed
var watcher = new System.IO.FileSystemWatcher();
watcher.Path = dir;
watcher.Filter = file;
// Open the file for reading and move to the end
var stream = new FileStream(dir + "\\" + file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Write | FileShare.Read);
stream.Seek(0, SeekOrigin.End);
var sr = new StreamReader(stream);
// In a separate thread, wait for changes, read any new data in the file and push them to the client
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback( v =>
{
while(StreamEnabled)
{
var change = watcher.WaitForChanged(System.IO.WatcherChangeTypes.Changed, 2000);
if (!change.TimedOut)
{
string newData = sr.ReadToEnd();
Console.WriteLine("Pushing update: " + newData.Trim());
// Decode the string into observation records
var records = DecodeData(newData);
// Push all observations to the client
foreach(var o in records)
callback.PushObservation(o);
}
}
Console.WriteLine("Stream ended.");
}));
}
示例12: Main
private static void Main(string[] args)
{
Process.Start("balloon.exe");
PandocPath = OpenFile("pandoc.exe");
LibrePath = OpenFile("soffice.exe");
DirectoryPath = OpenDirectory();
NotificationMessage("Starting", "Starting ext2conv2", ToolTipIcon.Info, 500);
while (true)
{
var watcher = new FileSystemWatcher();
watcher.Path = DirectoryPath;
watcher.Filter = "";
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.IncludeSubdirectories = true;
var changed = watcher.WaitForChanged(WatcherChangeTypes.All);
switch (changed.ChangeType)
{
case WatcherChangeTypes.Renamed:
var oldName = changed.OldName;
var oldExt = GetExtension(changed.OldName);
var name = changed.Name;
var ext = GetExtension(changed.Name);
if (oldExt != null && !oldExt.Equals(ext))
{
ShowResultMessage(WrappedConverter(oldExt, ext, oldName, name), oldName, name);
}
break;
}
}
}
示例13: Main
static void Main(string[] args)
{
var watch = Array.IndexOf(args, "-w");
if (watch < 0)
{
Environment.Exit(Run(args));
}
else
{
// First run may not exit with a startup or argument error
var code = Run(args);
if (-1 == code)
{
Environment.Exit(0xFF);
}
else if (2 == code)
{
Environment.Exit(2);
}
var watcher = new FileSystemWatcher {
Path = args[watch + 1],
IncludeSubdirectories = true,
Filter = "*.*"
};
using (watcher)
{
watcher.EnableRaisingEvents = true;
while (!watcher.WaitForChanged(WatcherChangeTypes.Changed).TimedOut)
{
Run(args);
}
}
Environment.Exit(0);
}
}
示例14: WaitTillDbCreated
//In case of self-host application activation happens immediately unlike iis where activation happens on first request.
//So in self-host case, we need a way to block the first request until the application is initialized. In MusicStore application's case,
//identity DB creation is pretty much the last step of application setup. So waiting on this event will help us wait efficiently.
private static void WaitTillDbCreated(string identityDbName)
{
var identityDBFullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), identityDbName + ".mdf");
if (File.Exists(identityDBFullPath))
{
Console.WriteLine("Database file '{0}' exists. Proceeding with the tests.", identityDBFullPath);
return;
}
Console.WriteLine("Watching for the DB file '{0}'", identityDBFullPath);
var dbWatch = new FileSystemWatcher(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), identityDbName + ".mdf");
dbWatch.EnableRaisingEvents = true;
try
{
if (!File.Exists(identityDBFullPath))
{
//Wait for a maximum of 1 minute assuming the slowest cold start.
var watchResult = dbWatch.WaitForChanged(WatcherChangeTypes.Created, 60 * 1000);
if (watchResult.ChangeType == WatcherChangeTypes.Created)
{
Console.WriteLine("Database file created '{0}'. Proceeding with the tests.", identityDBFullPath);
}
else
{
Console.WriteLine("Database file '{0}' not created", identityDBFullPath);
}
}
}
catch (Exception exception)
{
Console.WriteLine("Received this exception while watching for Database file {0}", exception);
}
finally
{
dbWatch.Dispose();
}
}
示例15: CheckSettings
/// <summary>
///
/// </summary>
/// <remarks>
/// From https://stackoverflow.com/questions/2269489/c-sharp-user-settings-broken
/// </remarks>
public static void CheckSettings()
{
try
{
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
}
catch (ConfigurationErrorsException ex)
{
string filename = string.Empty;
if (!string.IsNullOrEmpty(ex.Filename))
{
filename = ex.Filename;
}
else
{
var innerEx = ex.InnerException as ConfigurationErrorsException;
if (innerEx != null && !string.IsNullOrEmpty(innerEx.Filename))
{
filename = innerEx.Filename;
}
}
if (!string.IsNullOrEmpty(filename))
{
if (File.Exists(filename))
{
var fileInfo = new FileInfo(filename);
var watcher
= new FileSystemWatcher(fileInfo.Directory.FullName, fileInfo.Name);
Tools.WriteDebug(string.Format("Deleting corrupt file {0}", filename), ex.Message);
File.Delete(filename);
if (File.Exists(filename))
{
watcher.WaitForChanged(WatcherChangeTypes.Deleted);
}
}
}
}
}