The Pc I use have an UNC file. I'm in a Network with other people.
Every other can open the file by tipping in the adress line \\file.
Know I want to write a c# programm in Vs2010 which watch over the file I use Win7 32bit. If any one Open the file the programm shall write in a Logfile that someone has open my file.
I tried to use the FileSystemWatcher but this only look for changes/saves/cration but not for Opening.
I read somthing about "auditing" and that I'm be able to do that(watch over my unc file) with this(auditing).But i tried to find out how to use auditing in c# but i found not much.
.
So my Questions:
Is it possible to do what i want with "auditing" ?
Did someone worked with auditing in c# befor or has anyone a link or somtihng to show me how it works in c#?
mfg Sam
Sry for bad english
You might want to use the Audit Object Access.
The steps you have to follow:
Enable the Audit object access in the Local Computer Policy.
Enable auditing for the object you want to follow.
From your application, use the EventLog.EntryWritten Event to detect the file opening event
Here's a simplistic sample usage, but you'll have to dig in the documentation in order to capture and log as you need to:
class Program
{
public static void Main()
{
EventLog myNewLog = new EventLog("Security", ".", "Microsoft Windows security");
myNewLog.EntryWritten += new EntryWrittenEventHandler(MyOnEntryWritten);
myNewLog.EnableRaisingEvents = true;
Console.ReadLine();
}
public static async void MyOnEntryWritten(object source, EntryWrittenEventArgs e)
{
await Task.Factory.StartNew(() =>
{
if (e.Entry.InstanceId == 4656 || e.Entry.InstanceId == 4663)
{
Console.WriteLine(e.Entry.Message);
}
});
}
}
Related
I am using the JitBit Macro Recorder to create "bots" that save me a lot of time at work. This program can use the mouse and the keyboard and perform tasks by checking different if-options like "if image found on screen".
My newest "bot" is about 900 lines of commands long and I would like to make a log-file to find an error somewhere in there. Sadly, this program doesn't offer such an option, but it let's me use c# as a task. I have NO experience with c# but I thought, that this is easy to do for someone who has some experience.
If I click execute c# code, I get the following input field:
Important: This code MUST contain a class named "Program" with a static method "Main"!
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
Now I need two code templates:
1. Write a message to a "bot_log.txt" located on my desktop.
[19.05.2016 - 12:21:09] "Checking if item with number 3 exists..."
The number "3" changes with every run and is an exact paste of the clipboard.
2. Add an empty line to the same file
(Everything should be added to a new line at the end of this file.)
If you have no idea how to program in C#, then you should learn it,
if you want to use code provided from answers.
And if you want to generate timestamps and stuff then it's not done within minutes and I don't think someone writes the whole code just for your fitting. Normally questions should have at least a bit of general interest.
Anyway:
This works, if you have a RichTextTbox in your program.
Just do a new event (like clicking a button) and do this inside it.
(This was posted somewhere here too or on another site, with sligh changes)
public static void SaveMyFile(RichTextBox rtb)
{
// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveLog = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the RTF extention for the file.
saveLog.DefaultExt = "*.rtf";
saveLog.Filter = "RTF Files|*.rtf"; //You can do other extensions here.
// Determine whether the user selected a file name from the saveFileDialog.
if (saveLog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveLog.FileName.Length > 0)
{
// Save the contents of the RichTextBox into the file.
try
{
rtb.SaveFile(saveLog.FileName);
}
catch
{
MessageBox.Show("Error creating the file.\n Is the name correct and is enough free space on your disk\n ?");
}
MessageBox.Show("Logfile was saved successful.");
}
}
I've created a windows service project that will use the TiffCP exe in order to split any tiff files its found into multiple tiff files. I'm using the code that was given as an example on the site:
public static class SplitTiffImage
{
public static void Main()
{
string[] arguments =
{
#"Sample Data\multipage.tif,1",
"SplitTiffImage_2ndPage.tif"
};
TiffCP.Program.Main(arguments);
Process.Start("SplitTiffImage_2ndPage.tif");
}
}
This works as expected and splits the file. However, a process is created (MSPVIEW.EXE) and I'm unable to access the file because it is being edited in another program. I have to manually kill the process to access it. I've also tried creating the process as a variable and then trying to close or kill it but that doesn't seem to be working either. Any ideas? Thanks.
Edit: I've put this code before accessing the process again and when the service stops and it seems to do the trick. It works but I'm wondering if there is a better way.
Process[] process = Process.GetProcessesByName("MSPVIEW");
if (process.Length > 0)
{
foreach (var p in process)
{
p.Kill();
}
}
Remove the
Process.Start("SplitTiffImage_2ndPage.tif");
from the code above.
The line opens the output in a default viewer. In your case it's Microsoft Office Document Imaging (MSPVIEW.EXE). You clearly don't need the output to be opened in a viewer.
How can I get the number of times a program has previously run in c# without keeping a file and tallying. Is there a Application class or something in c# to check the count.
Please give a detailed explantion as i know nothing about it.This is A windows console application not windows forms.
You can do that my creating an Entry in the Registry. And another way is by using an Application Settings.
But I prefer Application Settings because it has less task to do.
See HERE: Creating an Application Settings.
Tutorial From Youtube
Recent versions of Windows automatically maintain this information in the registry under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist.
The data is obfuscated with ROT13, but that's easy to "decrypt". A free utility (with source code) is available and can serve as your starting point.
You could send a message to a database or webservice every time the program starts up (assuming there's a network connection).
You could keep a count on some form of hardware thet's not a standard storage device (therefore not technically being a file).
You could make a registry entry that you keep the count in (if you ignore the fact that the registry entry is, at some level, persisted into a file somewhere).
You could just have a file somewhere that keeps track of the count. Not sure why you're so opposed to this one in the first place....
If you are running a Winforms application, the you can easily use the Application Settings. Right click on your Solution Name --> Properties --> Settings Tab. More info and tutorial here.
Then, every time your program starts, increment this setting and save it.
Ref: Count the number of times the Program has been launched
In my knowledge Windows does not keep this information for you. You would have to tally the value somewhere (file, database, registry setting).
Better way is Application Settings as:
Create setting in app.config and then use it as:
Properties.Settings.Default.FirstUserSetting = "abc";
then, you usually do this in the Closing event handler of the main form. The following statement to Save settings method.
Properties.Settings.Default.Save();
Implementation using Registry:
static string AppRegyPath = "Software\\Cheeso\\ApplicationName";
static string rvn_Runs = "Runs";
private Microsoft.Win32.RegistryKey _appCuKey;
public Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegyPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegyPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
public int UpdateRunCount()
{
int x = (Int32)AppCuKey.GetValue(rvn_Runs, 0);
x++;
AppCuKey.SetValue(rvn_Runs, x);
return x;
}
If it's a WinForms app, you can hook the Form's OnClosing event to run UpdateCount.
Then Check tutorial to Read, write and delete from registry with C#
I would like to be notified in my C# application when another process makes changes to a particular textfile.
The reason for this is that I launch a 3rd party tool from my application in order to retrieve some information about a device. this tool saves the current state of the device into an ini file. This takes some undetermined time, but I want to react and read the state information as soon as it's available.
How can I do this?
You could use the System.IO.FileSystemWatcher class.
Something like this:
string fileToWatch = #"C:\MyFile.txt";
fileSystemWatcher = new FileSystemWatcher(fileToWatch);
void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
Debug.WriteLine(e.Name + " has changed");
}
You can monitor file changes using System.IO.FileSystemWatcher
Also, see Notification when a file changes? for more info.
I am building a windows forms application using C# that needs to get launched when a user clicks on a file with custom extension(eg. filename.mycustomextension)
I plan to put a url in the filename.mycustomextension file. when user clicks on this file, we winform application should launch and also read contents of this file.
Is it possible to do this?
First and most obviously you'll need to associate the file extension with the application either by "open with" in the shell, through an installer or directly in the registry.
MSDN - Best Practices for File Associations
Then from there it's really pretty simple.
static class Program
{
[STAThread]
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
string text = File.ReadAllText(args[1]);
// ...
}
}
args[0] is the application path.
args[1] will be the file path.
args[n] will be any other arguments passed in.
Offhand I can't find any examples that show all of this together simply but Scott Hanselman has a nice example of loading files through a single instance WinForms application, about the same...
http://www.hanselman.com/blog/CommentView.aspx?guid=d2f676ea-025b-4fd6-ae79-80b04a34f24c
Yes, it is possible.
The idea is that when your application is clicked, you modify the registry key, to associate the extension file with your application.
Here are the sketches:
Use the FileAssociation class from here.
Initialize it, set all the parameters.
Here is an example:
var FA = new FileAssociation();
FA.Extension = "blah";
FA.ContentType = "application/blah";
FA.FullName = "blah Project File";
FA.ProperName = "blahFile";
FA.AddCommand("open", string.Format("\"{0}\" \"%1\"", System.Reflection.Assembly.GetExecutingAssembly().Location));
//"C:\\mydir\\myprog.exe %1");
FA.IconPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
FA.IconIndex = 0;
FA.Create();
If you plan to launch your application from a browser then there are security issues, but other than that - yes.
You just need to install the application on the user's machine and associate your .mycustomextension with the application. http://support.microsoft.com/kb/185453