C# : filesystemwatcher class - c#

i have a question about the moving file event on filesystemwatcher class , i`d like to stop the moving of file or edit it when the moving file event arises for a certain file , is that possible to handle inside the moving event ?

No, there is no way to stop someone moving or renaming a file using the FileSystemWatcher class.
If you look, none of the event arguments passed by the events on the FileSystemWatcher class have a Cancel property. Also, the fact that the class is simply called a Watcher is a bit of a clue.
You might consider using Access Control Lists to make sure someone cannot delete a file (since a move is really just a copy/delete). Or perhaps you could try opening a FileStream on the file so that you have it locked.

You cannot directly "cancel" the operation by means of the event handler. You would have to provide a compensating operation to programatically "undo" any changes you want undone.

You only receive the events after the fact has happened. It's a mere notification, not an event you'd have to approve. This can also be guessed from the missing Cancel or Handled property in the FileSystemEventArgs (as opposed to, for example, the KeyEventArgs) class.
You can detect a move and try to move the file back, based on the OldFullPath property of the RenamedEventArgs you receive.
This might however be confusing to your users or to other software. And try not to end up in an infinite loop, where you move the file back and forth every time you receive the event.

Related

Handling wpf drop of external programs

I'm trying to fiddle with an idea, and one big concept is dropping programs, bookmarks, etc. I have what I believe to be the gist of it but I'm not receiving any information
private void Border_Drop(object sender, DragEventArgs e)
{
FileInfo[] files = (FileInfo[])e.Data.GetData(DataFormats.FileDrop);
foreach (FileInfo file in files)
{
Writer.Text += file.FullName;
}
}
Though my textblock is never populated? I'd like to get all the properties of File such as FullName, Name, Extension, DirectoryName, etc.
Any pointers on where to go from here? I've been trying to read the MSDN of the event but nothing is coming up, and I've searched stackoverflow and nothing is working for my case scenario.
One possible reason is that you have attached the event handler to the wrong control. Try attaching the event handler to the Form, or if that does not work, the textblock.
I would also highly recommend doing some debugging. Place a breakpoint in the event handler to see if it is called, and if so, what happens in it.
WPF has two different routed event handling mechanisms: bubbling and tunneling. Bubbling is the "normal" way to do it, and tunneling is when you see all those PreviewThis and PreviewThat in the event name. It's possible, that another control has aready marked the event as handled, and so you don't see it in your event handler.
If you need documentation for WPF drag and drop, read this
If you need some really custom, really low level stuff on this subject, you can also read up on Object Linking and Embedding This is probably how drag-and-drop is implemented in Word so that you can drag images and Excel tables into Word documents and they will display natively. But to use this you will probably need to use some Win32 API calls which is a bit of a bummer.

Check property changes without timer (C#)

Let's say,
I have an instance of FileInfo,
I want my program to check for file changes and
the FileInfo class doesn't provide events for that task.
Is there a better way than using a timer to check the FileInfo's properties and throw an event, if those properties changed?
I want to check a file for changes without opening it.
FileSystemWatcher.Changed event is what you are looking for.

C# Form Application: How to avoid deleting the unwanted events "manually" from InitializeComponent()?

This is a simple scenario:
I add an event to a control on the form by double clicking on its field (in Events part). But, then I decide that it was unnecessary and delete the automatically generated method. I'll run the program and it gives an error telling me that the event still exists in the InitializeComponent() and I must delete it from there.
So, is there anyway to avoid deleting the event "manually"? Is there anyway to fully delete it without leaving any trace (specially in InitializeComponent())?
Update: Also, another question arose:
When I delete the method from the code, the method name in the event field will disappear. So, if the InitializeComponent() is linked to these events, why isn't it updated with the empty event field?
You should use again the events grid and right click on the event you have inserted.
Select the Reset Menu option. This will remove the event handler assigned in the InitializeComponent and the code of the emtpy event in the code designer.
Note, that if you add code at the event, Visual Studio doesn't remove the new code.
The best way to do this is through the Properties grid in the Designer. You can click the Reset button or just delete the text and it will remove the event hook-up in the InitializeComponent() method. If your method is empty in your code behind, it will also delete it there:
It makes sense that you would have to manually delete the method body if it contains code in case it accidentally got Reset in the designer or if your method is referenced from some other part of your code. Visual Studio is gong to err on the side of caution.
If you delete the method body first, the reason it is not deleting the references to it probably in part has to do with cutting-and-pasting code. If you wanted to move the method to a different place in your code, the acting of cutting it would sever the references to it. After you pasted it, then you would wonder why your event was no longer be called. Again, error on the side of caution since it's not that difficult for the developer to track down extraneous code.
This pertains to C# 2017. So hopefully it would help others.
I'm new to C# (or at least back to code it) and ran with the same issue.
I commented out the event that I did by mistake. Then in the Error list, you will find an error there because that event is missing. Double click on it. It'll take you to the Designer code that "wires" the event. Once there, find the unwanted event and comment it out/delete it. Take care!
Look at the properties window when you select the Control. Click on the little flash and you'll see the Events listed, along with your event (Click or whatever), and your event will have the name of the assigned method behind it. Just delete that method.
That deletes the method, only if it's empty and otherwise unused though, which is quite reasonable. After all you might have put a lot of work into that event handler. (note: Just tried it again and apparently it doesn't always delete empty methods even though it did a few minutes ago. weird.)
In the designer you go to the events tab for the control in question, select the event that has the unwanted handler; and delete the name of the handler. Then save the form again.
This doesn't delete the method itself I think, (possibly unless it's empty or just been added).
Update
I dare say the reason for why it nearly always doesn't delete the method is because it could be used as a handler on another control's event. After all, in the UI you only asked to remove one event's handler; not every handler bound to that method. Then there's the question of whether the back-end code is dirty (i.e. unsaved) - checking whether the method is empty or not isn't reliable in that case. Yes, all of these could be worked around, but having to delete the method manually isn't exactly a hardship :) and at least this way VS doesn't end up deleting methods you actually want to keep.
Go back to the form and hit CTRL+Z.

stream textfile to textbox c#

Suppose i have a textfile which continuous to be updated with text, how can i display the contents in a textbox in windows form (in real-time)?
for example. this is the contents of log.txt:
connected, bla bla bla
disconnected, bla bla bla
PS: i want it to be displayed in textBox of Form1 (real time also) so everytime the text file has new text, the textbox displays it. Any ideas, pls help. thanks. also can u provide a sample working code. thanks
Use a FileSystemWatcher
Use the example on MSDN (see the link above) you can add a event handler to Changed Event
and update your textbox from there.
Just call Application.DoEvents(); once you've updated your text. But note that updating too often might cause flicker as well as slow down your overall processing. Also note that this is error prone if any drawing/update code causes updates/draws again (infinite recursion).
Edit: Read half the question ...
Add a FileSystemWatcher to watch for changes to the log file. However this is a very ineffective approach and depending on the settings used to write the log file you might be missing access rights and/or the file might update only when the application closes. If both processes are your own code and you're able to modify them, you should think about other possibilities (e.g. a simple "server" you can connect to using some telnet (or custom) client).
Insert a RichTextBox and a FilesystemWatcher, and a textbox or something else to store the path and filename of the text file you want to show. Now, go to the FilesystemWatcher_Changed (or whatever it's called) event. There you put an if that checks if the changed file is the one you want to be shown, and then RichTextBox.LoadFile(file).
What this is going to do is monitor the fileystsem (hard disk or any folder you specify), and every time a file has cha nged, it's going to check if it's the file that we're looking at. If it is, it's going to reload the file into the RichTextBox.
Don't forget to set the RaiseEvent and Path properties of the FilesystemWatcher.
Example:
string blaFile = "C:\TextFile.txt"; // The text file that we want to read.
private void FilesystemWatcher_Changed(....).... // The FilesystemWatcher_Changed event notifies us when a file on the monitored path (FilesystemWatcher.Path) has changed. When a file has changed the code within this event gets executed.
{
if (e.File == blaFile) // We check if the file that has chenged, is the one we want.
{
RichTextBox.LoadFile(blaFile); // It is! We load it into the RichtextBox again so that it's "up-to-date"!
}
}
I'm not completely sure about the e.File as I haven't used C# in a while now, but it's something like that.
It is not suggested to use text file, since there are two processes to access the file and you require real-time update.
Try to use NamePipeServerStream and NamePipeClientStream for two processes memory sharing.

C# Progress Bar within a class?

Simply put, what is a good way to send the progress of some process back to a form from within a class outside the scope of the form?
EG: I have a Input object, a filepath is sent into the constructor of this object and it parses the file. I want to show the progress of reading in the lines of this file back to the user who is in a form outside the scope of the currently running method. Ultimately I will be displaying overall progress and per file progress.
Add an event to your class that the form can subscribe to. UpdateProgress or something like that. Your class would then raise the event every so often to let the form display the progress.
The best approach here would be a BackgroundWorker. It has a specal event ReportProgress (that handles the Invoke logic for you).
It is an easy way to do multi-threading. Follow a good example when implementing the RunWorkerCompleted event.

Categories

Resources