Click here to Skip to main content
15,220,495 members

Monitoring Access to Your Shared Files on Network

Rate this:
4.71 (15 votes)
Please Sign up or sign in to vote.
4.71 (15 votes)
9 Mar 2010CPOL
ShareMonitor allows you to monitor any access to your network shared files
Image 1


ShareMonitor allows you to monitor any access to your network shared files. When a user remotely opens shared files on your computer, the application detects it and displays information such as who opened it, when it was opened, duration, etc. about that file. All details will be logged and can be saved to .CSV or .XML files for further analysis.
You can also disconnect any active connection whenever you want.

Using the Code

Using “OpenFiles.exe”, it queries opened files in regular periods of time. It continuously compares sequence of OpenFiles.exe outputs and updates the data table. For newly opened files, it inserts related data into a data table. Next time if the file is not still open, it sets it as closed and stores closed time for that file and repeats this routine.

OpenFiles.exe” was the simplest way possible to find out access to shared resources. Of course there must some Windows API for it and it's better to use them but they seems to be undocumented and I couldn't find anything. Please let me know if you found any related Windows API.

As I tested the program, I noticed that it can't show non-English (Unicode) file names. As this problem refers to output of OpenFiles.exe, I couldn't fix it by code-page manipulating.

Note: OpenFiles.exe is a Windows tool that shows shared files which are currently opened by others. This file is in WINDOWS\system32 folder.


Openfiles.exe output has some information such as connection ID, user who accessed the file, filename, etc. These data are stored in a data table that is created in the code below. There is an extra boolean column named "Closed" which holds the state of the shared file: still in use or closed.

private void PrepareDataTable()
    dataTable = new DataTable("ShareMonitor");
    dataTable.Columns.Add("Opened at", typeof(DateTime));
    dataTable.Columns.Add("Closed at", typeof(DateTime));
    dataTable.Columns.Add("Duration", typeof(TimeSpan));

    dataTable.Columns.Add("Host Name");
    dataTable.Columns.Add("ID", typeof(int));
    dataTable.Columns.Add("User Name");
    dataTable.Columns.Add("Open Mode");

    dataTable.Columns.Add("Closed", typeof(bool));

    dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ID"] };

RefreshData() is the main method of application which is run periodically by a timer. In this method, I create a new process and execute openfiles.exe with "/query /FO CSV /v" parameters. These parameters mean that I want to get a detailed comma-separated list of shared files which are currently in use.

RedirectStandardOutput property lets you get the process output (which is sent to the console).

Before reading the output (lines), I set all unclosed connections to "closed". This is because they may be closed since the last check and I may not find them in current openfiles output anymore.

Finally, I check the lines string variable. Each line represents one file connection. If connection ID does not exist in the datatable, I insert it as a new open connection. Otherwise, if connection ID exists in datatable, it means that the connection was opened before and is still open. So I set the "Closed" field to false and clear "Closed at" field.

By setting FirstDisplayedScrollingRowIndex property of the grid, you can be assured that newly added connections will be shown in the grid. Something that we call auto scrolling grid rows.

private void RefreshData()
    var process = new Process();
    process.StartInfo.FileName = "openfiles.exe";
    process.StartInfo.Arguments = "/query /FO CSV /v";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.RedirectStandardOutput = true;
        if ((process.StandardOutput != null))
            var result = process.StandardOutput.ReadToEnd().Trim().Replace("\"", "");
            var lines = result.Split('\n');
            foreach (DataRow row in dataTable.Rows)
                //set all previous open connections to closed because 
                //they may not be still in use!
                var closed = row.Field<bool?>("Closed");
                if (closed == null || closed.Value == false)
                    row["Closed"] = true;
                    row["Closed at"] = DateTime.Now.ToString("G");
                    if (row["Duration"] == DBNull.Value)
                        row["Duration"] = ((DateTime)row["Closed at"]) - 
			((DateTime)row["Opened at"]);

            var firstLineIndex = 1 + lines.Cast<string>().ToList().FindIndex
				(l => l.Contains("Hostname"));
            for (int i = firstLineIndex; i < lines.Count() && firstLineIndex > 0; i++)
                var fields = lines[i].Split(',');
                var row = dataTable.Rows.Find(fields[1]); //ID
                if (row == null) 	//it is a new file and not exists 
				//in datatable... so add it
                    var newRow = dataTable.NewRow();
                    newRow["Opened at"] = DateTime.Now.ToString("yyyy MM dd HH:mm:ss");
                    newRow["Host Name"] = fields[0];
                    newRow["ID"] = fields[1];
                    newRow["User Name"] = fields[2];
                    newRow["Type"] = fields[3];
                    newRow["Locks"] = fields[4];
                    newRow["Open Mode"] = fields[5];
                    newRow["File/Folder"] = fields[6];

                    //auto scroll
                    var gridRow = grdMain.Rows.Cast<DataGridViewRow>().
                        Where(r => (r.DataBoundItem as DataRowView).Row.Field<int>("ID") 
				== newRow.Field<int>("ID")).
                    if (gridRow != null)
                        grdMain.FirstDisplayedScrollingRowIndex = gridRow.Index;

                else  //it is still in use and not closed
                    row["Closed"] = false;
                    row["Closed at"] = DBNull.Value;

            //auto size columns
    catch (Exception e)
        lblMsg.Text = " Error: " + e.Message + " : " + DateTime.Now.ToShortTimeString();


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Alan Zavari
Software Developer (Senior)
United States United States
Blog: C# Tips

Comments and Discussions

QuestionProblem Pin
sa98i10-Dec-16 19:54
Membersa98i10-Dec-16 19:54 
GeneralMy vote of 5 Pin
satya raaz mali18-Nov-10 15:22
Membersatya raaz mali18-Nov-10 15:22 
GeneralRe: My vote of 5 Pin
Simon Clifton Cardenas4-Jan-11 20:22
MemberSimon Clifton Cardenas4-Jan-11 20:22 
GeneralHardcoded for English Language - Not for Located Windows Versions Pin
Member 335868730-Jun-10 5:54
MemberMember 335868730-Jun-10 5:54 
GeneralRe: Hardcoded for English Language - Not for Located Windows Versions Pin
Alan Zavari30-Jun-10 6:01
MemberAlan Zavari30-Jun-10 6:01 
GeneralWindows API NetFileEnum Pin
axuno18-Mar-10 12:49
Memberaxuno18-Mar-10 12:49 
GeneralRe: Windows API NetFileEnum Pin
Alan Zavari20-Mar-10 9:36
MemberAlan Zavari20-Mar-10 9:36 
GeneralRe: Windows API NetFileEnum Pin
Truedarkside28-Apr-10 9:23
MemberTruedarkside28-Apr-10 9:23 
GeneralRe: Windows API NetFileEnum Pin
Alan Zavari2-May-10 1:51
MemberAlan Zavari2-May-10 1:51 
GeneralNice Job Pin
Amir Razmjou9-Mar-10 2:12
MemberAmir Razmjou9-Mar-10 2:12 
GeneralRe: Nice Job Pin
Alan Zavari9-Mar-10 2:14
MemberAlan Zavari9-Mar-10 2:14 
Generalerror Pin
mikejobu238-Mar-10 10:10
Membermikejobu238-Mar-10 10:10 
GeneralRe: error Pin
Alan Zavari8-Mar-10 17:35
MemberAlan Zavari8-Mar-10 17:35 
GeneralRe: error Pin
mikejobu239-Mar-10 2:00
Membermikejobu239-Mar-10 2:00 
AnswerRe: error (FIXED) Pin
Alan Zavari9-Mar-10 7:23
MemberAlan Zavari9-Mar-10 7:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 8 Mar 2010


57 bookmarked