简体   繁体   中英

How to detect and determine file changes?

I am currently using a FileWatcher ( FileSystemWatcher.OnChanged ) to detect when a file is changed. I am wondering if there is a way to determine how a file changes.

For example, I have a .txt that contains the following: Hello world! . It then gets edited and saved so that it reads Hello world! Goodbye world! Hello world! Goodbye world! . Is there a more elegant way to get the added text in the file ( Goodbye world! ) without doing something like saving the original text as a string variable, then comparing it to the new text when a file change is detected? This method could work if text was only added to the file, but what if text is deleted or changed, ie it changes to Hello or Hello friend! )?

There is no way to detect the type of change with the granularity you request. Whoever is modifying the file could always read the entire file into a string and add and remove some words and then write the string back, making the semantics of the change (ie append/prepend/insert/remove/...) opaque to the operating system. In fact, this is how 99% of programs operate on text files.

Diffing tools (as, for instance, used in SCMs) can help reconstruct a possible set of changes. But yes, you will need to keep a copy of the original file around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM