本文整理汇总了C#中System.IO.FileSystemWatcher.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# FileSystemWatcher.Dispose方法的具体用法?C# FileSystemWatcher.Dispose怎么用?C# FileSystemWatcher.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileSystemWatcher
的用法示例。
在下文中一共展示了FileSystemWatcher.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
//srcで指定されたPDFファイルをページ毎に分割し、destで指定されたパスに保存する。
//保存ファイル名は「ファイル名-ページ番号.pdf」とする。
//分割したページ数を返す。
public List<string> Run(string src, string dest)
{
// srcで渡されたファイルが存在するか?
if (!File.Exists(src))
{
throw new FileNotFoundException();
}
// destで渡されたフォルダが存在するか?
if (!Directory.Exists(dest))
{
throw new DirectoryNotFoundException();
}
var reader = new iTextSharp.text.pdf.PdfReader(src);
string file_name = Path.GetFileNameWithoutExtension(src);
int digit = reader.NumberOfPages.ToString().Length;
var app_name = new MainForm();
// 一時フォルダにpdfを作成してdestにコピー。
// その際上書き確認を行う。
System.IO.DirectoryInfo del = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text);
if (del.Exists) del.Delete(true);
System.IO.DirectoryInfo tmp = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text);
tmp.Create();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
var doc = new iTextSharp.text.Document();
var dest_tmp = String.Format(@"{{0}}\{{1}}-{{2:D{0}}}.pdf", digit);
var dest_name = String.Format(dest_tmp, tmp, file_name, i);
var copy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(dest_name, FileMode.Create));
doc.Open();
copy.AddPage(copy.GetImportedPage(reader, i));
doc.Close();
}
// コピーしたファイルを監視する
Ret.list.Clear();
var watcher = new System.IO.FileSystemWatcher();
watcher.Path = dest;
watcher.Filter = "*.pdf";
watcher.Changed += new FileSystemEventHandler(changed);
watcher.Created += new FileSystemEventHandler(changed);
watcher.EnableRaisingEvents = true;
FileSystem.CopyDirectory(tmp.ToString(), dest, UIOption.AllDialogs);
watcher.EnableRaisingEvents = false;
watcher.Dispose();
watcher = null;
tmp.Delete(true);
reader.Close();
return Ret.list;
}
示例2: WatchForChanges
public static IObservable<string> WatchForChanges(string path,string filter,bool recursive)
{
var isDirectory = new DirectoryInfo(path).Exists;
recursive = isDirectory && recursive;
var fileSystemWatcher = new FileSystemWatcher(path)
{
Filter = filter,
IncludeSubdirectories = recursive
};
fileSystemWatcher.EnableRaisingEvents = true;
var observable = fileSystemWatcher.AsObservable()
.ObserveOn(TaskPoolScheduler.Default)
.Select(e => e.FullPath)
.Buffer(TimeSpan.FromSeconds(1))
.Where(e => e.Any())
.Select(e => e.Distinct())
.SelectMany(e => e);
var connectableObservable = observable.Publish();
connectableObservable.Connect();
connectableObservable.Subscribe((v) => log.Info("Detected file system change, root: {0}, change: {1}",path,v), (ex) => fileSystemWatcher.Dispose(), fileSystemWatcher.Dispose);
return connectableObservable;
}
示例3: Test_FileSystemWatcher_01
public static void Test_FileSystemWatcher_01()
{
string path = @"c:\Users\Pierre\AppData\Local\Temp";
string filter = "*.cmdline";
_tr.WriteLine("Test_FileSystemWatcher_01 \"{0}\" \"{1}\"", path, filter);
FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.Filter = filter;
watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Changed);
watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
try
{
watcher.EnableRaisingEvents = true;
while (true)
{
//if (_wr.Abort)
if (_wr.IsExecutionAborted())
break;
}
}
finally
{
watcher.EnableRaisingEvents = false;
watcher.Dispose();
if (__fs != null)
{
__fs.Close();
__fs = null;
}
}
}
示例4: DisposeFileWatcher
void DisposeFileWatcher(FileSystemWatcher fileWatcher)
{
fileWatcher.EnableRaisingEvents = false;
fileWatcher.Changed -= BranchWatcher_Changed;
fileWatcher.Renamed -= BranchWatcher_Renamed;
fileWatcher.Dispose();
}
示例5: ObserveChanges
public static IObservable<Unit> ObserveChanges(this PathSpec path, NotifyFilters filters)
{
var parent = path.Parent();
if (!parent.HasValue) return Observable.Never<Unit>();
return Observable.Create<Unit>(observer =>
{
var watcher = new FileSystemWatcher(parent.Value.ToString())
{
IncludeSubdirectories = false,
Filter = path.Name,
EnableRaisingEvents = true,
NotifyFilter = filters
};
var subscription = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(handler => watcher.Changed += handler, handler => watcher.Changed -= handler)
.Select(_ => Unit.Default)
.Subscribe(observer);
return new AnonymousDisposable(() =>
{
subscription.Dispose();
watcher.Dispose();
});
});
}
示例6: Add
public void Add(string path, bool includeSubdirectories)
{
var folderDisposable = new CompositeDisposable();
var watcher = new System.IO.FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter =
(System.IO.NotifyFilters.LastAccess
| System.IO.NotifyFilters.LastWrite
| System.IO.NotifyFilters.FileName
| System.IO.NotifyFilters.DirectoryName);
watcher.Filter = "*";
watcher.IncludeSubdirectories = includeSubdirectories;
var changed =
Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>
(h => (sender, e) => h(e), h => watcher.Changed += h, h => watcher.Changed -= h)
.Select(x => new RxFileSystemEventArgs(x.ChangeType, x.FullPath, null, path));
var created =
Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>
(h => (sender, e) => h(e), h => watcher.Created += h, h => watcher.Created -= h)
.Select(x => new RxFileSystemEventArgs(x.ChangeType, x.FullPath, null, path));
var deleted =
Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>
(h => (sender, e) => h(e), h => watcher.Deleted += h, h => watcher.Deleted -= h)
.Select(x => new RxFileSystemEventArgs(x.ChangeType, x.FullPath, null, path));
var renamed =
Observable.FromEvent<RenamedEventHandler, RenamedEventArgs>
(h => (sender, e) => h(e), h => watcher.Renamed += h, h => watcher.Renamed -= h)
.Select(x => new RxFileSystemEventArgs(x.ChangeType, x.FullPath, x.OldFullPath, path));
var subscription = Observable
.Merge(changed, created, deleted, renamed)
.Subscribe(this.FolderChangedSubject);
watcher.EnableRaisingEvents = true;
Disposable.Create(() =>
{
watcher.EnableRaisingEvents = false;
subscription.Dispose();
watcher.Dispose();
})
.AddTo(this.Watchers, path);
}
示例7: Start
public async Task Start(IState initialState, Session session,
CancellationToken cancellationToken = default(CancellationToken))
{
var state = initialState;
var profilePath = Path.Combine(Directory.GetCurrentDirectory(), "");
var profileConfigPath = Path.Combine(profilePath, "config");
FileSystemWatcher configWatcher = new FileSystemWatcher();
configWatcher.Path = profileConfigPath;
configWatcher.Filter = "config.json";
configWatcher.NotifyFilter = NotifyFilters.LastWrite;
configWatcher.EnableRaisingEvents = true;
configWatcher.Changed += (sender, e) =>
{
if (e.ChangeType == WatcherChangeTypes.Changed)
{
session.LogicSettings = new LogicSettings(GlobalSettings.Load(""));
configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents;
configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents;
Logger.Write(" ##### config.json ##### ", LogLevel.Info);
}
};
do
{
try
{
state = await state.Execute(session, cancellationToken);
}
catch (InvalidResponseException)
{
session.EventDispatcher.Send(new ErrorEvent
{
Message = "Niantic Servers unstable, throttling API Calls."
});
}
catch (OperationCanceledException)
{
session.EventDispatcher.Send(new ErrorEvent {Message = "Current Operation was canceled."});
state = _initialState;
}
catch (Exception ex)
{
session.EventDispatcher.Send(new ErrorEvent {Message = "Pokemon Servers might be offline / unstable. Trying again..."});
Thread.Sleep(1000);
session.EventDispatcher.Send(new ErrorEvent { Message = "Error: " + ex });
state = _initialState;
}
} while (state != null);
configWatcher.EnableRaisingEvents = false;
configWatcher.Dispose();
}
示例8: Start
public void Start()
{
HostedService service = CreateNewAppDomain();
var watcher = new FileSystemWatcher(path);
bool wasCalled = false;
var @lock = new object();
FileSystemEventHandler handler = (sender, e) =>
{
string extension = Path.GetExtension(e.FullPath);
if (extension != ".dll" && extension != ".config" && extension != ".exe")
return;
watcher.Dispose();
lock (@lock)
{
if (wasCalled)
return;
wasCalled = true;
logger.WarnFormat("Got change request for {0}, disposing current AppDomain",
e.Name);
service.Stop();
Thread.Sleep(500); //allow for other events to happen
logger.Warn("Restarting...");
Start();
}
};
watcher.Deleted += handler;
watcher.Changed += handler;
watcher.Created += handler;
watcher.EnableRaisingEvents = true;
current = service;
try
{
service.Start();
}
catch (ReflectionTypeLoadException e)
{
var sb = new StringBuilder();
foreach (var exception in e.LoaderExceptions)
{
sb.AppendLine(exception.ToString());
}
throw new TypeLoadException(sb.ToString(), e);
}
}
示例9: WhenPathChanges
public static IObservable<string> WhenPathChanges(string path, string filter)
{
return Observable.Create<string>(observer =>
{
var watcher = new FileSystemWatcher(path, filter);
var changed = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Changed += h, h => watcher.Changed -= h);
var deleted = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Deleted += h, h => watcher.Deleted -= h);
var created = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Created += h, h => watcher.Created -= h);
watcher.EnableRaisingEvents = true;
return
changed
.Merge(deleted)
.Merge(created)
.Select(e => e.EventArgs.FullPath)
.Throttle(TimeSpan.FromMilliseconds(100))
.Finally(() => watcher.Dispose())
.Subscribe(observer);
});
}
示例10: Watch
public IDisposable Watch(DirectoryInfo scriptPath)
{
var watcher = new FileSystemWatcher(scriptPath.FullName);
watcher.BeginInit();
watcher.Path = scriptPath.FullName;
watcher.EnableRaisingEvents = true;
watcher.Error += OnError;
watcher.Changed += OnChanged;
watcher.Created += OnCreated;
watcher.Deleted += OnDeleted;
watcher.Renamed += OnRenamed;
watcher.EndInit();
return new Disposable(() => watcher.Dispose());
}
示例11: For
public IObservable<FileEvent> For(string fullFilePath, string extensionFilter)
{
return Observable.Create<FileEvent>(obs =>
{
var fileName = Path.GetFileName(fullFilePath);
var dir = Path.GetDirectoryName(fullFilePath);
var watcher = new FileSystemWatcher(dir, extensionFilter);
var onCreated =
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Created += h,
h => watcher.Created -= h)
.Select<EventPattern<FileSystemEventArgs>, FileEvent>(
args => new FileCreated(args.EventArgs.FullPath, args.EventArgs.Name));
var onChanged =
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Changed += h,
h => watcher.Changed -= h)
.Select<EventPattern<FileSystemEventArgs>, FileEvent>(
args => new FileChanged(args.EventArgs.FullPath, args.EventArgs.Name));
var onRenamed =
Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>(h => watcher.Renamed += h,
h => watcher.Renamed -= h)
.Select<EventPattern<RenamedEventArgs>, FileEvent>(
ev =>
new FileRenamed(ev.EventArgs.FullPath, ev.EventArgs.Name, ev.EventArgs.OldFullPath,
ev.EventArgs.OldName));
var combined = onCreated.Merge(onChanged).Merge(onRenamed)
.Where(ev => ev.Name == fileName)
.Subscribe(obs);
watcher.EnableRaisingEvents = true;
return Disposable.Create(() =>
{
combined.Dispose();
watcher.Dispose();
});
});
}
示例12: FileSystemWatcher
public void Check_how_does_the_file_system_watcher_work_when_creating_file_and_editing_when_watching_at_the_file_size()
{
var watcher = new FileSystemWatcher(Environment.CurrentDirectory);
bool wasRaised = false;
watcher.Created += (s, a) =>
{
Console.WriteLine("Created file ");
Assert.That(a.Name, Is.EqualTo(name));
wasRaised = true;
};
watcher.Changed += (s, a) => Console.WriteLine("Was modified" );
watcher.NotifyFilter = NotifyFilters.FileName| NotifyFilters.Size;
watcher.EnableRaisingEvents = true;
var stopwatch = new Stopwatch();
Console.WriteLine("Creating");
using (var stream = new FileStream(name, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
var writer = new StreamWriter(stream);
Thread.Sleep(100);
stopwatch.Start();
Console.WriteLine("Writing");
for (int i = 0; i < fileSize; i++)
{
writer.WriteLine("{0}", i);
}
Thread.Sleep(100);
Console.WriteLine("Flushing");
writer.Flush();
Thread.Sleep(100);
Console.WriteLine("Disposing");
writer.Dispose();
stopwatch.Stop();
}
Console.WriteLine("Time elapsed " + stopwatch.ElapsedMilliseconds);
Console.WriteLine("File size " + new FileInfo(name).Length);
Thread.Sleep(100);
Assert.That(wasRaised);
watcher.Dispose();
}
示例13: SetupWatchers
public void SetupWatchers(IEnumerable<string> files)
{
if (files == null)
return;
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
if (fileInfo.Directory == null)
throw new IOException("File Path has no directory to watch");
if(FileSystemWatchers.ContainsKey(file))
continue;
Console.WriteLine("Started watching '{0}' for changes", file);
var directoryFullName = fileInfo.Directory.FullName;
var fsWatcher = new FileSystemWatcher(directoryFullName, fileInfo.Name);
fsWatcher.Changed += FsWatcherChanged;
fsWatcher.EnableRaisingEvents = true;
FileSystemWatchers[file] = fsWatcher;
}
var missing = FileSystemWatchers.Keys.Where(f => !files.Contains(f)).ToList();
foreach (var file in missing)
{
var fsWatcher = FileSystemWatchers[file];
fsWatcher.Changed -= FsWatcherChanged;
fsWatcher.Dispose();
FileSystemWatchers.Remove(file);
Console.WriteLine("Stopped watching '{0}'", file);
}
}
示例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: StopWatching
private void StopWatching(FileSystemWatcher watcher)
{
InternalLogger.Info("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter);
watcher.EnableRaisingEvents = false;
watcher.Dispose();
}