Displaying / finding open file path in C #
I want to write a program, when I open the file and view the file that is in the file e: \ test \ test.doc, then I want to pass the path into a separate filetracing.txt file.
If I open the file in f: \ doc.pdf, the output should be:
the file in "e:\test.doc" is opened on 2.30 am
the file in "f:\doc.pdf" is opened on 8.30 am like wise
How do I write a program to do this in C #?
a source to share
Did you mean that you want the application to write to the log file when the c: \ file is accessed ?
If so, there is a possible solution that includes the System.IO.FileSystemWatcher class. (I would link to the MSDN docs, but since I'm new here I can't)
The FileSystemWatcher class is intended more for watching changes in the file system rather than accessing the direct file system. Therefore, with this solution, you are limited to observing LastAccessed changes - this is not always updated and therefore should rely on strict audit reasons.
Here's a quick snippet of code to demonstrate using a FileSystemWatcher to monitor LastAccessed changes:
using (var w = new System.IO.FileSystemWatcher("c:\\"))
{
w.IncludeSubdirectories = true;
w.NotifyFilter = NotifyFilters.LastAccess;
w.Changed += (object sender, FileSystemEventArgs e) =>
{
Console.WriteLine("{0} {1} at {2}", Path.Combine(e.FullPath, e.Name), e.ChangeType, DateTime.Now);
};
w.EnableRaisingEvents = true;
Console.WriteLine("Press Enter to exit");
Console.Read();
}
Notes:
-
This receives events when in some file it has a LastAccessed property which includes file creation and modification.
-
If you go to the same drive you are looking at, you will receive your own Write events, so be sure to filter them out.
using System.IO;
string path = "e: \ test \ test.txt"
// store your path in a string
File FileStream = new FileStream (path, FileMode, FileAccess); // opens file test.doc
// perform file operation
file.close ();
// open path file
FileStream pathfile = new FileStream ("filetracing.txt", FileMode, FileAccess);
StreamWriter sw = new StreamWriter (path file);
sw.Write (path); // path string will be written in filetracing.txt
sw.Close (); pathfile.Close ();
a source to share
You can create a small monitoring app that can only work with the UI of the notification icon and implement the FileSystemWatcher class to view the files and fire the log event if needed
Example using FileSystemWatcher below
a source to share