public WaitForChanged ( System changeType ) : System.IO.WaitForChangedResult | ||
changeType | System | |
리턴 | System.IO.WaitForChangedResult |
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; } } }
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!"); }
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}); }
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(); }
public static void WaitForFileOperations(string directory, string fileOperation, int timeOutInSeconds) { log.Info("Waiting For File " + fileOperation + "operation...\n max timeout is" + timeOutInSeconds + " seconds"); System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(directory); switch (fileOperation) { case "created": watcher.WaitForChanged(System.IO.WatcherChangeTypes.Created, timeOutInSeconds * 1000); log.Info("A file is created"); break; case "deleted": watcher.WaitForChanged(System.IO.WatcherChangeTypes.Deleted, timeOutInSeconds * 1000); log.Info("A file is deleted"); break; case "changed": watcher.WaitForChanged(System.IO.WatcherChangeTypes.Changed, timeOutInSeconds * 1000); log.Info("A file is changed"); break; case "renamed": watcher.WaitForChanged(System.IO.WatcherChangeTypes.Renamed, timeOutInSeconds * 1000); log.Info("A file is renamed"); break; case "all": watcher.WaitForChanged(System.IO.WatcherChangeTypes.All, timeOutInSeconds * 1000); log.Info("A file is created/deleted/changed/renamed"); break; default: log.Error("invalid file operation provided.." + fileOperation); break; } }
/// <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(); }
/// <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; }
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); }
/// <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; } }
public void watchSystemdrive() { var fsw = new System.IO.FileSystemWatcher("c:\\"); if (!IsWatching) { fsw.Changed += Fsw_Changed; IsWatching = true; while (IsWatching) { //fsw.SynchronizingObject. var result = fsw.WaitForChanged(System.IO.WatcherChangeTypes.All); this.Warning($"{result.ChangeType}: '{result.Name}'."); } } }
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); } }
/// <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; } }
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."); })); }
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; } } }
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); } }
/// <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); } } } } }
private void OpenInEditor() { isEditing = true; if (!File.Exists(CurrentScreenshot.InternalFileName)) { Directory.CreateDirectory(Path.GetDirectoryName(CurrentScreenshot.InternalFileName)); CurrentScreenshot.ComposedScreenshotImage.Save(CurrentScreenshot.InternalFileName, ImageFormat.Png); } Windowing.ShellExecute(IntPtr.Zero, "edit", CurrentScreenshot.InternalFileName, string.Empty, string.Empty, Windowing.ShowCommands.SW_NORMAL); var fsw = new FileSystemWatcher(Path.GetDirectoryName(CurrentScreenshot.InternalFileName), "*" + Path.GetExtension(CurrentScreenshot.InternalFileName)); fsw.Changed += (s_fsw, e_args) => this.BeginInvoke(new Action(() => WriteCompleteCheck.Enabled = true)); var async = new BackgroundWorker(); async.DoWork += (o, a) => fsw.WaitForChanged(WatcherChangeTypes.Changed); async.RunWorkerAsync(); }
private void WatchFile() { try { string dir = Path.GetDirectoryName(this.filePath); string file = Path.GetFileName(this.filePath); FileInfo fileInfo = new FileInfo(filePath); fileInfo.Refresh(); long fileLength = fileInfo.Length; using (FileSystemWatcher watcher = new FileSystemWatcher(dir, file)) { watcher.EnableRaisingEvents = false; bool stop = false; this.context.Response.SendChunked = true; this.context.Response.OutputStream.Flush(); while (!stop) { WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.All, (int)this.idleTimeout.TotalMilliseconds); if (result.TimedOut) { stop = true; break; } if (result.ChangeType == WatcherChangeTypes.Renamed || result.ChangeType == WatcherChangeTypes.Deleted) { stop = true; break; } else if (result.ChangeType == WatcherChangeTypes.Changed || result.ChangeType == WatcherChangeTypes.Created) { try { long newFileLength = new FileInfo(filePath).Length; if (newFileLength != 0) { int bytesToRead = (int)(newFileLength - fileLength); if (bytesToRead > 0) { using (FileStream tailFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { tailFile.Seek(bytesToRead * -1, SeekOrigin.End); try { tailFile.CopyTo(this.context.Response.OutputStream); this.context.Response.OutputStream.Flush(); } catch (HttpListenerException) { stop = true; break; } } } fileLength = newFileLength; } } catch { stop = true; break; } } } } } catch (Exception ex) { Logger.Error(Strings.ErrorSettingUpFileSystemWatcher, ex.ToString()); this.context.Response.ContentType = MediaTypeNames.Text.Plain; this.context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; using (StreamWriter writer = new StreamWriter(this.context.Response.OutputStream)) { writer.Write(string.Format(CultureInfo.InvariantCulture, Strings.ErrorSettingUpFileSystemWatcher, ex.Message)); } } finally { this.context.Response.OutputStream.Flush(); this.context.Response.Close(); } }
/// Entry point public int Run(Arguments args) { using (var w = new FileSystemWatcher { Path = args.Path, IncludeSubdirectories = args.Recursive, Filter = "*.*" }) { w.Error += new ErrorEventHandler(OnWatcherError); // Parse "events" argument WatcherChangeTypes changes = 0; if (args.Events.Contains("create")) { changes |= WatcherChangeTypes.Created; } if (args.Events.Contains("modify")) { changes |= WatcherChangeTypes.Changed; } if (args.Events.Contains("delete")) { changes |= WatcherChangeTypes.Deleted; } if (args.Events.Contains("move")) { changes |= WatcherChangeTypes.Renamed; } // Main loop if (!args.Quiet) { Console.Error.WriteLine( "===> {0} for {1} in {2}{3} for {4}", args.Monitor ? "Monitoring" : "Watching", changes, args.Path, args.Recursive ? " -r" : "", String.Join(", ", args.Events.ToArray()) ); } w.EnableRaisingEvents = true; do { var e = w.WaitForChanged(changes); if (WatcherChangeTypes.Renamed.Equals(e.ChangeType)) { Output(Console.Out, args.Format, w, Change.MOVE_FROM, e.OldName); Output(Console.Out, args.Format, w, Change.MOVE_TO, e.Name); } else { Output(Console.Out, args.Format, w, Changes[e.ChangeType], e.Name); } } while (args.Monitor); } return 0; }
static void Main(string[] args) { string dir = Directory.GetCurrentDirectory() +"\\iv_data";// // dir = @"C:\Users\cowdo\Documents\WirelessTracer\iv_catcher\iv_curve_catcher\iv_curve_catcher\bin\Debug\iv_data\"; FileSystemWatcher watcher = new FileSystemWatcher(dir); string pgm = @"C:\Program Files\gnuplot\bin\pgnuplot.exe"; if (args.Length > 0) { pgm = args[0]; } Console.WriteLine("using gnu plot @ " + pgm); Thread.Sleep(400); Process extPro = new Process(); extPro.StartInfo.FileName = pgm; extPro.StartInfo.UseShellExecute = false; extPro.StartInfo.RedirectStandardInput = true; extPro.Start(); // XmlSerializer iv_xml = new XmlSerializer(typeof(Raw_IV_Curve)); StreamWriter gnupStWr = extPro.StandardInput; while (true) { WaitForChangedResult res = watcher.WaitForChanged(WatcherChangeTypes.All,int.MaxValue); if (res.TimedOut) { continue; } if (res.Name.Contains(".csv")) { Thread.Sleep(1000); try { string fn = Path.Combine(dir, res.Name); string[] lines = File.ReadAllLines(fn); DateTime filetime = File.GetCreationTime(fn); List<float> V = new List<float>(); List<float> C = new List<float>(); float Vmpp = 0; float Impp = 0; float mpp = 0; foreach (string l in lines) { try { string[] f = l.Split(','); float v = float.Parse(f[1]); float c = float.Parse(f[0]); V.Add(v); C.Add(c); if (c * v > mpp) { mpp = c * v; Vmpp = v; Impp = c; } } catch (Exception ex) { } } // TextReader reader = new StreamReader( fn ); // Raw_IV_Curve curve = (Raw_IV_Curve)iv_xml.Deserialize(reader); // string csv_file = res.Name.Replace(".txt", ".csv"); int index = res.Name.LastIndexOf('a'); string address = res.Name.Substring(index + 1, res.Name.LastIndexOf('.') - index); gnupStWr.WriteLine("reset"); gnupStWr.Flush(); gnupStWr.WriteLine("set term wxt " + address); gnupStWr.Flush(); gnupStWr.WriteLine("set style data linespoints"); gnupStWr.Flush(); gnupStWr.WriteLine("set grid"); gnupStWr.Flush(); gnupStWr.WriteLine("set datafile separator \",\""); gnupStWr.Flush(); gnupStWr.WriteLine("set output \"last_iv.png\""); gnupStWr.Flush(); gnupStWr.WriteLine(string.Format("set title \"File : {0}\"", res.Name)); gnupStWr.Flush(); gnupStWr.WriteLine("set xlabel \"Voltage(V)\""); gnupStWr.Flush(); gnupStWr.WriteLine("set ylabel \"Current(A)\""); gnupStWr.Flush(); gnupStWr.WriteLine(string.Format("set label \" Peak Power = {0} Watts \" at {1},{2}", mpp.ToString("F2"), Vmpp, Impp)); gnupStWr.Flush(); gnupStWr.WriteLine("set style line 1 lc rgb '#0060ad' lt 1 lw 2 pt 7 ps .4"); gnupStWr.Flush(); gnupStWr.WriteLine("set autoscale"); gnupStWr.Flush(); //string file = fn;// @"C:\Users\cowdo\Documents\WirelessTracer\iv_catcher\iv_curve_catcher\iv_curve_catcher\bin\Debug\iv_data\2013_77_47895_a13.csv"; gnupStWr.WriteLine(string.Format("plot '{0}' using 2:1 title \'{1} {2}\' with linespoints ls 1", fn, filetime.ToShortDateString(), filetime.ToShortTimeString())); gnupStWr.Flush(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, Encoding fileEncoding) { if (this.stream != null) { this.fileOffset = this.stream.Position; this.stream.Close(); } FileInfo info = new FileInfo(filePath); using (FileSystemWatcher watcher = new FileSystemWatcher(info.DirectoryName, info.Name)) { watcher.EnableRaisingEvents = true; while (!this.provider.Stopping) { if (!watcher.WaitForChanged(WatcherChangeTypes.All, 500).TimedOut) { goto Label_0076; } } } Label_0076: Thread.Sleep(100); this.CreateStreams(filePath, null, fileMode, fileAccess, fileShare, fileEncoding); if (this.fileOffset > this.stream.Length) { this.fileOffset = 0L; } this.stream.Seek(this.fileOffset, SeekOrigin.Begin); if (this.reader != null) { this.reader.DiscardBufferedData(); } if (this._backReader != null) { this._backReader.DiscardBufferedData(); } }
private void butOK_Click(object sender, System.EventArgs e) { double amtDebt=PIn.Double(textAmount.Text); if(amtDebt==0){ MessageBox.Show("Please fill in an amount."); return; } if(amtDebt<25) { MessageBox.Show("Amount of debt must be at least $25.00."); return; } if(amtDebt>9999999.00) {//limit 10 char MessageBox.Show("Amount of debt is unreasonably large."); return; } DateTime dateDelinquency=PIn.Date(textDate.Text); if(dateDelinquency.Year<1950) { MessageBox.Show("Date is not valid."); return; } if(dateDelinquency>DateTime.Today) { MessageBox.Show("Date cannot be a future date."); return; } if(!Regex.IsMatch(textPassword.Text,@"^[A-Z]{2}\d{4}$")) { MessageBox.Show("Password is not in correct format. Must be like this: AB1234"); return; } if(textPassword.Text!=PrefC.GetString(PrefName.TrojanExpressCollectPassword)){//user changed password Prefs.UpdateString(PrefName.TrojanExpressCollectPassword,textPassword.Text); DataValid.SetInvalid(InvalidType.Prefs); } Cursor=Cursors.WaitCursor; string folderPath=PrefC.GetString(PrefName.TrojanExpressCollectPath); if(folderPath==""){ Cursor=Cursors.Default; MessageBox.Show("Export folder has not been setup yet. Please go to Setup at the top of this window."); return; } if(!folderPath.EndsWith("\\")){ folderPath+="\\"; } if(!File.Exists(folderPath+"TROBEN.HB")){ Cursor=Cursors.Default; MessageBox.Show("The Trojan Communicator is not installed or is not configured for the folder: " +folderPath+". Please contact Trojan Software Support at 800-451-9723 x1 or x2"); return; } File.Delete(folderPath+"TROBEN.HB"); FileSystemWatcher watcher=new FileSystemWatcher(folderPath,"TROBEN.HB"); WaitForChangedResult waitResult=watcher.WaitForChanged(WatcherChangeTypes.Created,10000); if(waitResult.TimedOut){ Cursor=Cursors.Default; MessageBox.Show("The Trojan Communicator is not running. Please check it."); return; } long billingType=PrefC.GetLong(PrefName.TrojanExpressCollectBillingType); if(billingType==0){ Cursor=Cursors.Default; MessageBox.Show("Billing type has not been setup yet. Please go to Setup at the top of this window."); return; } StringBuilder str=new StringBuilder(); if(radioDiplomatic.Checked){ str.Append("D*"); } else if(radioFirm.Checked) { str.Append("F*"); } else if(radioSkip.Checked) { str.Append("S*"); } str.Append(Clip(patCur.LName,18)+"*"); str.Append(Clip(patCur.FName,18)+"*"); str.Append(Clip(patCur.MiddleI,1)+"*"); str.Append(Clip(guarCur.LName,18)+"*");//validated str.Append(Clip(guarCur.FName,18)+"*");//validated str.Append(Clip(guarCur.MiddleI,1)+"*"); str.Append(guarCur.SSN.Substring(0,3)+"-"+guarCur.SSN.Substring(3,2)+"-"+guarCur.SSN.Substring(5,4)+"*");//validated if(guarCur.Birthdate.Year<1880){ str.Append("*"); } else{ str.Append(guarCur.Birthdate.ToString("MM/dd/yyyy")+"*"); } str.Append(Clip(guarCur.HmPhone,13)+"*"); if(empCur==null){ str.Append("**"); } else{ str.Append(Clip(empCur.EmpName,35)+"*"); str.Append(Clip(empCur.Phone,13)+"*"); } string address=guarCur.Address;//validated if(guarCur.Address2!=""){ address+=", "+guarCur.Address2; } str.Append(Clip(address,30)+"*"); str.Append(Clip(guarCur.City,20)+"*");//validated str.Append(Clip(guarCur.State,2)+"*");//validated str.Append(Clip(guarCur.Zip,5)+"*");//validated str.Append(amtDebt.ToString("F2")+"*");//validated str.Append(dateDelinquency.ToString("MM/dd/yyyy")+"*");//validated str.Append(textPassword.Text+"*");//validated str.Append(Clip(Security.CurUser.UserName,25)+"\r\n");//There is always a logged in user int thisNum=TrojanQueries.GetUniqueFileNum(); string outputFile="CT"+thisNum.ToString().PadLeft(6,'0')+".TRO"; File.AppendAllText(folderPath+outputFile,str.ToString()); watcher=new FileSystemWatcher(folderPath,outputFile); waitResult=watcher.WaitForChanged(WatcherChangeTypes.Deleted,10000); if(waitResult.TimedOut) { Cursor=Cursors.Default; MessageBox.Show("Warning!! Request was not sent to Trojan within the 10 second limit."); return; } Patients.UpdateFamilyBillingType(billingType,patCur.Guarantor); Cursor=Cursors.Default; DialogResult=DialogResult.OK; }
/// <summary> /// Main EntryPoint /// </summary> static void Main() { #region CreateRsyncProcessStartInfo rsyncProcessStartInfo.FileName = Settings.Default.RsyncPath; rsyncProcessStartInfo.Arguments = CreateRsyncArgs(); rsyncProcessStartInfo.CreateNoWindow = true; rsyncProcessStartInfo.UseShellExecute = false; rsyncProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden; #endregion #region Console Console.WriteLine($"watching:{Settings.Default.LocalPath}"); #endregion #region IntervalMode if (Settings.Default.IntervalSeconds > 0) { new Thread(new ThreadStart(() => { while (true) { Thread.Sleep(IntervalTimeSpan); if (Settings.Default.NotifyMode) { Console.WriteLine("rsync by interval"); } Rsync(false); } })).Start(); } #endregion #region Watch using (var fileSystemWatcher = new FileSystemWatcher(Settings.Default.LocalPath)) { fileSystemWatcher.EnableRaisingEvents = true; fileSystemWatcher.Created += (o, e) => { if (Settings.Default.NotifyMode) { Console.WriteLine($"rsync by created: {e.FullPath}"); } Rsync(); }; fileSystemWatcher.Deleted += (o, e) => { if (Settings.Default.NotifyMode) { Console.WriteLine($"rsync by deleted: {e.FullPath}"); } Rsync(); }; fileSystemWatcher.Changed += (o, e) => { if (Settings.Default.NotifyMode) { Console.WriteLine($"rsync by changed: {e.FullPath}"); } Rsync(); }; fileSystemWatcher.Renamed += (o, e) => { if (Settings.Default.NotifyMode) { Console.WriteLine($"rsync by renamed: {e.OldFullPath} -> {e.FullPath}"); } Rsync(); }; while (true) { fileSystemWatcher.WaitForChanged(WatcherChangeTypes.All); } } #endregion }
internal static bool WaitForFileMessage(TimeSpan timeout, string absolutePath, string fileName) { try { using (FileSystemWatcher watcher = new FileSystemWatcher(absolutePath, fileName)) { watcher.EnableRaisingEvents = true; WaitForChangedResult result; int time; time = (timeout.TotalMilliseconds > Int32.MaxValue) ? Int32.MaxValue : timeout.Milliseconds; result = watcher.WaitForChanged(WatcherChangeTypes.Changed, time); return !result.TimedOut; } } catch (IOException exception) { throw ConvertException(exception); } }
public override bool WaitForStateChange(TimeSpan timeout) { var fsWatcher = new FileSystemWatcher(_stateFile.DirectoryName, StateFileName); var res = fsWatcher.WaitForChanged(WatcherChangeTypes.All, (int) timeout.TotalMilliseconds); return !res.TimedOut; }
private void SFLWait() { System.IO.WaitForChangedResult result; System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(Application.StartupPath + "\\kf2_ds\\KFGame\\Config\\", "PCServer-KFSystemSettings.ini"); result = watcher.WaitForChanged(System.IO.WatcherChangeTypes.Created); Thread.Sleep(20000); foreach (Process Serv in System.Diagnostics.Process.GetProcessesByName("KFServer")) { Serv.Kill(); Serv.WaitForExit(); } LoadInfo(); }
private void Window_Initialized(object sender, EventArgs e) { OneTimePassWindow otpw = null; DispatcherFrame dispacherFrame = null; var thread = new Thread(() => { try { var dataJson = DynamicJson.Parse(File.ReadAllText("data.json", new UTF8Encoding())); var wc = new WebClientEx() { Encoding = new UTF8Encoding() }; if (dataJson["proxy"] != "") { wc.Proxy = new WebProxy(string.Format("http://{0}/", dataJson["proxy"])); } wc.Headers.Add("Referer","http://arad.nexon.co.jp/"); var str = wc.DownloadString("http://www.nexon.co.jp/login/"); var unique_id = new Regex( "return document.getElementById\\('(.*?)'\\).value;" ).Matches(str)[0].Groups[1].Value; var unique_password = Regex.Replace(unique_id,"^i","p"); var entm = new Regex( "name=(\"|')entm(\"|') value=(\"|')(.*?)(\"|')" ).Matches(str)[0].Groups[4].Value; var data = new NameValueCollection(); data.Add( "entm", entm ); data.Add(unique_id, dataJson["id"]); data.Add(unique_password, dataJson["password"]); data.Add( "onetimepass", "" ); data.Add("HiddenUrl","http://arad.nexon.co.jp/"); data.Add( "otp", "" ); wc.Headers.Add( "Referer", "http://www.nexon.co.jp/login/" ); str = Encoding.UTF8.GetString( wc.UploadValues( "https://www.nexon.co.jp/login/login_process1.aspx?iframe=true", data)); // When onetimepass require if( str.Contains( "location.replace(\"https://www.nexon.co.jp/login/otp/index.aspx" ) ) { str = wc.DownloadString( new Regex( "location\\.replace\\(\"(https://www.nexon.co.jp/login/otp/index\\.aspx.*?)\"\\)" ).Matches(str)[0].Groups[1].Value ); dispacherFrame = new DispatcherFrame( true ); otpw = new OneTimePassWindow(); otpw.Closed += ( o, args ) => { dispacherFrame.Continue = false; }; otpw.ShowDialog(); Dispatcher.PushFrame( dispacherFrame ); var onetimepass = otpw.otp; data = new NameValueCollection(); data.Add( "otp" , onetimepass); wc.UploadValues( new Regex( "action=\"(.*?)\" id=\"otploginform\"" ).Matches( str )[0].Groups[1].Value, data ); } str = wc.DownloadString("http://arad.nexon.co.jp/launcher/game/GameStart.aspx"); var parameters = new List<string>(); parameters.Add(new Regex("\\[\"ServerIP\"\\] = \"(.*?)\"").Matches(str)[0].Groups[1].Value); parameters.Add(new Regex("\\[\"ServerPort\"\\] = \"(.*?)\"").Matches(str)[0].Groups[1].Value); parameters.Add(new Regex("\\[\"ServerType\"\\] = \"(.*?)\"").Matches(str)[0].Groups[1].Value); parameters.Add(new Regex("\\[\"SiteType\"\\] = \"(.*?)\"").Matches(str)[0].Groups[1].Value); parameters.Add(new Regex("\\[\"UserId\"\\] = \"(.*?)\"").Matches(str)[0].Groups[1].Value); parameters.Add(new Regex("\\[\"PassportString\"\\] = \"(.*?)\"").Matches(str)[0].Groups[1].Value); parameters.Add(new Regex("\\[\"LauncherChecksum\"\\] = \"(.*?)\"").Matches(str)[0].Groups[1].Value); parameters.Add(new Regex("\\[\"CharCount\"\\] = \"(.*?)\"").Matches(str)[0].Groups[1].Value); Process.Start("neoplecustomurl://" + string.Join("/", parameters)); // Delete Arad.lnk if exists if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Arad.lnk")) { File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Arad.lnk"); } // monitoring Arad.lnk var watcher = new FileSystemWatcher(); watcher.Path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); watcher.Filter = "Arad.lnk"; watcher.NotifyFilter = NotifyFilters.FileName; // exclude subdirectories watcher.IncludeSubdirectories = false; // start monitoring var changedResult = watcher.WaitForChanged(WatcherChangeTypes.Created); // Delete Arad.lnk when created if (changedResult.ChangeType == WatcherChangeTypes.Created) { // wait for another process file handle dispose Thread.Sleep(500); File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Arad.lnk"); Environment.Exit(0); } } catch (Exception ex) { MessageBox.Show(ex.Message); Environment.Exit(0); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); }
public bool WaitForRequest(TimeSpan timeout) { ThrowIfDisposedOrNotOpen(); try { File.Delete(PathToFile(LocalAddress.Uri, "request")); using (FileSystemWatcher watcher = new FileSystemWatcher(LocalAddress.Uri.AbsolutePath, "request")) { watcher.EnableRaisingEvents = true; WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Changed, (int)timeout.TotalMilliseconds); return !result.TimedOut; } } catch (IOException exception) { throw ConvertException(exception); } }
//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(); } }
public void Processor(object data) { string path = (string)data; using (var w = new FileSystemWatcher { Path = path, IncludeSubdirectories = _args.Recursive, Filter = "*.*" }) { w.Error += new ErrorEventHandler(OnWatcherError); // Parse "events" argument WatcherChangeTypes changes = 0; if (_args.Events.Contains("create")) { changes |= WatcherChangeTypes.Created; } if (_args.Events.Contains("modify")) { changes |= WatcherChangeTypes.Changed; } if (_args.Events.Contains("delete")) { changes |= WatcherChangeTypes.Deleted; } if (_args.Events.Contains("move")) { changes |= WatcherChangeTypes.Renamed; } // Main loop if (!_args.Quiet) { Console.Error.WriteLine( "===> {0} for {1} in {2}{3} for {4}", _args.Monitor ? "Monitoring" : "Watching", changes, path, _args.Recursive ? " -r" : "", String.Join(", ", _args.Events.ToArray()) ); } w.EnableRaisingEvents = true; while (true) { var e = w.WaitForChanged(changes); _mutex.WaitOne(); if (_eventOccured) { _mutex.ReleaseMutex(); break; } if (WatcherChangeTypes.Renamed.Equals(e.ChangeType)) { Output(Console.Out, _args.Format, w, Change.MOVE_FROM, e.OldName); Output(Console.Out, _args.Format, w, Change.MOVE_TO, e.Name); } else { Output(Console.Out, _args.Format, w, Changes[e.ChangeType], e.Name); } if (!_args.Monitor) { _eventOccured = true; _semaphore.Release(); } _mutex.ReleaseMutex(); } } }
internal static bool WaitForDirectoryChannel(TimeSpan timeout, string directoryName) { try { using (FileSystemWatcher watcher = new FileSystemWatcher("C:\\", directoryName)) { watcher.EnableRaisingEvents = true; WaitForChangedResult result; int time; time = (timeout.TotalMilliseconds > Int32.MaxValue) ? Int32.MaxValue : timeout.Milliseconds; result = watcher.WaitForChanged(WatcherChangeTypes.Created, time); return !result.TimedOut; } } catch (IOException exception) { throw ConvertException(exception); } }
private void WatchForChanges() { var watcher = new FileSystemWatcher(tacker.BaseDir); watcher.IncludeSubdirectories = true; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Changed += new FileSystemEventHandler (OnChanged); watcher.Created += new FileSystemEventHandler (OnChanged); watcher.Deleted += new FileSystemEventHandler (OnChanged); watcher.Renamed += new RenamedEventHandler (OnChanged); // Begin watching. watcher.EnableRaisingEvents = true; while (true) { watcher.WaitForChanged (WatcherChangeTypes.All); } }