Get the location of windows event log files - c#

We are using EventLog to log exceptions. there is a background thread which check once the eventlog get full and programmaticaly transfers the entries into an XML file and then clear the event log.
This works fine but it seems like there is too much work getting done, I thought it would be better to simply copy the .evt file used for logging the current application and then clear the event log.
is there any way to find the location/path of the file which will work on every windows OS?
its suggested to use
Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\EventLog\\" + e.Log);
but then my application log names dont have a File property.

How are you archiving them now? Maybe that method can be improved to gain performance.
Here's an example.
EventLogSession els = new EventLogSession();
els.ExportLogAndMessages("Security", // Log Name to archive
PathType.LogName, // Type of Log
"*", // Query selecting all events
"C:\\archivedLog.evtx", // Exported Log Path
false, // Stop archive if query is invalid
CultureInfo.CurrentCulture);
Or you can use the ClearLog() method.
EventLogSession els = new EventLogSession();
// Clears all the events and archives them to the .evtx file
els.ClearLog("System", // Channel to Clear
"c:\\myLog.evtx"); // Backup File Path
More information can be found here:
Export, Archive, and Clear Event Logs

Related

Is there a way to check if there are any files uploading to an azure storage account container?

I've got an api that allows a user to create a container in a storage account and then upload an unlimited number of files. At the point they've finished triggering the uploads they can trigger a process that will start validating those files and downloading to another machine. They can trigger this process before the uploads have finished.
So I was hoping to find a way where I can check whether a container has any file uploads in progress. I've not been able to find anything other than workarounds to track whether specific files are still uploading. I need to make a call to a container and see if anything is in progress or not.
• Yes, there is a way through which you can check whether the container has any file uploads in progress or not but for that purpose, you will have to use the ‘FileUpload’ control option along with a Boolean value to verify whether that control has a file to upload or not. In addition, the ‘File.Exists’ method is called to check whether a file with the same name already occurs in the path. If it does, the name of the file to upload is prefixed with an underscore character before the ‘SaveAs’ method is called.
Thus, atleast through this method, you can determine which files are in upload queue from a particular directory to the container. Please find the below snapshots and code snippets for your reference: -
protected void UploadButton_Click(object sender, EventArgs e)
{
// Before attempting to save the file, verify
// that the FileUpload control contains a file.
if (FileUpload1.HasFile)
// Call a helper method routine to save the file.
SaveFile(FileUpload1.PostedFile);
else
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
The above section of code states whether the file to be uploaded is present in the directory or not while the one below tries to find out whether a file with the same name already exists in the given path or not and prefixes it with a number so that when this file is being uploaded and queried for further, it can be identified.
if (System.IO.File.Exists(pathToCheck))
{
int counter = 2;
while (System.IO.File.Exists(pathToCheck))
{
// if a file with this name already exists,
// prefix the filename with a number.
tempfileName = counter.ToString() + fileName;
pathToCheck = savePath + tempfileName;
counter ++;
}
To know more details regarding this, I would suggest you to please refer the below link: -
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.fileupload.hasfile?view=netframework-4.8#examples
https://www.educba.com/asp-dot-net-fileupload/

C# OpenFileDialog multiple filename filters including exclude

I have a requirement to allow users to open a specific file for processing. The open file dialog is currently
OpenFileDialog ofg = new OpenFileDialog
{
FileName = "BaseFileName*",
Filter = "CSV File (*.CSV)|*.csv",
Multiselect = false,
InitialDirectory = #"N:\Downloads"
};
However the process adds a suffix of _Processed along with timestamp data to the filename and I want to exclude these renamed files the next time the OpenFileDialog is used to prevent the user trying to reprocess the same file.
I have to leave the original files where they are for internal audit reasons.
So I need an additional filename filter of not equal to "_Processed".
Is there any way to do this with OpenFileDialog or does anyone know of a custom c#/.net component that can do this?
You are asking to omit specific items from the file dialog view.
According to MSDN, this is no longer possible as of Windows 7, but was possible previously.
The C# file dialogs (both WPF and WinForms) use the IFileDialog API.
Here is the function that could have made this work, but is no longer supported:
https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfilter
As it is, you are stuck with checking the file for correctness after the user has already selected it and confirmed it with OK.
You can help the situation a little bit: If you enjoy pain, then you can copy the whole IFileDialog COM interop code from the .NET source code, and implement IFileDialogEvents. This way, when the user clicks "OK", you can deny the selection and display an error before the dialog closes, leaving the dialog open so the user can select a different file.
If you are sane and you don't want to do that, then you'll have to open the dialog again after the verification fails.
The easy way is just saving the processed data with another extension e.g. "BaseFileName_Processed_20105640640.cvs1", that way you keep the data and your file dialog will not show this file.
Another way could be to call the OpenFileDialog() in an if statement (and compare the return to DialogResult.OK), then split the file name for {'_','.'}, then run a loop to count the occurrences of the word Processed( >0), and possibly as a safety check determine whether a timestamp is present in one of the split strings. Finally, reload the FileOpenDialog in the same folder when the wrong file was selected.

C# FileSystemWatcher file size is only updating with windows explorer

I've a problem with the FileSystemWatcher in C#.
I watch a file used by another program.
This is not a problem. The problem is that the only value that changes with the file is the size. The other program is writing the file without updating the change or write date.
And the size value is only updating when the (windows 7) explorer refreshing (F5, or clicked on the file).
FileSystemWatcher fileWatcher = new FileSystemWatcher();
fileWatcher.Changed += new FileSystemEventHandler(fileWatcher_Changed);
fileWatcher.Path = Path.GetDirectoryName(path); // get directory of file path.
fileWatcher.Filter = Path.GetFileName(path); // only this file
fileWatcher.NotifyFilter = NotifyFilter.Size; // and maybe other
fileWatcher.EnableRaisingEvents = true;
private void fileWatcher_Changed(object sender, FileSystemEventArgs e)
{
// ...
}
I guess that this problem can only be solved by polling. Because the file should be triggered for refreshing file info data.
But I hope for another solution without polling.
About my application:
Reading a file which is in use of another program. Getting the text of the file is possible with FileStream FileShare.ReadWrite. It's working fine. I want to update the textbox (reading the file) when the file has been changed. But the only value who is updating while the other program is accessing to it, is the file size. But only when the explorer is refreshing or I'm clicking on the file. This is the issue of this question. If the problem is unsolvable, the alternative is: updating the file content (reading file) all x time. (polling) without a file watcher.
Perhaps, following would solve your problem, and avoid polling. Try using WMI, querying root\cimv2 namespace with something like:
select filesize from 'cim_datafile' where name='_your_path_'
Might differ slightly when applied from C# but along those lines. Regarding WMI, there's lots of tutorials how to initialize a WMI listener in .NET. Search around.

testing for raised events by FileSystemWatcher

Hi I am currently trying to test failure of a change to the config file,
I use the following code to do this...
string path = _pathInvalidFormat.Substring(0, _pathInvalidFormat.LastIndexOf('\\'));
System.IO.File.Copy("TestInvalidXmlConfigurationFile.xml", _pathInvalidFormat, true);
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(path);
//catch the invalid file getting deleted
fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted);
//catch the temporary config file getting renamed
fileSystemWatcher.Renamed += new RenamedEventHandler(fileSystemWatcher_Renamed);
fileSystemWatcher.EnableRaisingEvents = true;
CreateConfig(_pathInvalidFormat);
System.Threading.Thread.Sleep(5000);
Assert.That(_oldFileDeleted);
Assert.That(_newFileCreated);
ResetConfig(_pathInvalidFormat);
However I am not happy with this use of System.Threading.Thread.Sleep(5000);
I have tried using fileSystemWatcher.WaitForChanged(WatcherChangeTypes.Deleted, 5000); but cant seem to get it to work, as it always just seems to reach the timeout. Even when I can see the Deleted event has been hit, it still doesn't return.
Alternatively is there a better way of getting the system to wait for asynchronous events to be fired?
Thanks
Kieran
-- edited:
I use createconfig(path) to create a system config file using the following method
private void ReadConfiguration(string path)
{
var configFileMap = new ExeConfigurationFileMap()
{
ExeConfigFilename = path,
};
// if we try to read bad formatted file let's
// 1. delete this file
// 2. call read configuration to form correct file
try
{
Config = System.Configuration.ConfigurationManager
.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
}
catch (ConfigurationErrorsException)
{
// ok, there is bad format file, let delete it and create another one
// TODO: check security rights?
File.Delete(path);
ReadConfiguration(path);
}
}
Hope this gives some insight as to what exactly my test is trying to achieve.
Put all the code in a function and execute it asynchronous with thread.
Now, you can use manual reset events of threading to execute further code after sleep when file has been deleted, renamed and invalid path error checked.
In this manner, code execution will be not blocked.
refer this link for example

FileSystemWatcher and Monitoring Config File Changes

I have about 5-6 Server Manager programs that write their own configuration file out to a particualr folder, such as C:\ACME. The config files all end with a *ServerConfig.cfg" where * = Program name that created it.
I have a Windows service that has a FileSystemWatcher setup that I want to FTP the configuration files each time the program updates. I've gotten everything to work, but I'm noticing that the different Server Manager programs are behaving differently.
When saving a configuration file, the FileSystemWatcher is picking up two "change" events. This is causing my program to FTP the configuration file twice where I only need it once.
In other instances I'm seeing where it may create 4, 5, or 6 "change" events when saving a configuration file.
What is the best way to handle processing/FTPing these files when they are really done saving only one time.
I really dont want o set something up to poll the directory for filechanges every so often... and like the idea that each time a configuration is saved, I get a duplicate copy along with a date/timestamp appended to the filename copied elsewhere.
I have seen lots of suggestions Googling around and even here on Stackoverflow, but nothing that seems to be all-in-one for me.
I suppose I could put the filename in a queue when a "change" event occurred if it didn't already exist in the queue. Not sure if this is the best approx.
Here is my sample code:
Startup-code:
private DateTime _lastTimeFileWatcherEventRaised = DateTime.Now;
_watcherCFGFiles = new FileSystemWatcher();
_watcherCFGFiles.Path = #"C:\ACME";
_watcherCFGFiles.IncludeSubdirectories = true;
_watcherCFGFiles.Filter = "*ServerConfig.cfg";
_watcherCFGFiles.NotifyFilter = NotifyFilters.Size;
//_watcherCFGFiles.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.FileName;
_watcherCFGFiles.Changed += new FileSystemEventHandler(LogFileSystemChanges);
_watcherCFGFiles.Created += new FileSystemEventHandler(LogFileSystemChanges);
_watcherCFGFiles.Deleted += new FileSystemEventHandler(LogFileSystemChanges);
_watcherCFGFiles.Renamed += new RenamedEventHandler(LogFileSystemRenaming);
_watcherCFGFiles.Error += new ErrorEventHandler(LogBufferError);
_watcherCFGFiles.EnableRaisingEvents = true;
Here is that actual handler for the "change" event. I'm skipping the first "change" event if the second is within 700ms. But this doesn't account for the files that make 3-4 change events...
void LogFileSystemChanges(object sender, FileSystemEventArgs e)
{
string log = string.Format("{0} | {1}", e.FullPath, e.ChangeType);
if( e.ChangeType == WatcherChangeTypes.Changed )
{
if(DateTime.Now.Subtract(_lastTimeFileWatcherEventRaised).TotalMilliseconds < 700)
{
return;
}
_lastTimeFileWatcherEventRaised = DateTime.Now;
LogEvent(log);
// Process file
FTPConfigFileUpdate(e.FullPath);
}
}
I had the exact same issue. I used a HashMap that mapped filenames to times of writes, I then used this as a lookup table for files to check and see if the changed event had been applied very quickly. I defined some epsilon (for me it was about 2 seconds to make sure events were flushed). If the time found in the map was older than that I would put it on a queue to be processed. Essentially all I had to do was keep the HashMap up to date with events and changes and this worked out (although you may want to change your epsilon value depending on your application).
Its normal this behavior because the antivirus system or other programs make more writes when a file change the content. I usually create a (global) HashTable and check if the filename exists, if don't, put the filename in it and start and an asynchronous operation to remove the filename after 3-5 seconds.
This is expected behavior - so you need to figure out how to handle it in your particular case.
The file system does not have a concept of "program done working with this file". I.e. one can write editor that updates (open/write/close) file on every keystroke. File system will report a lot of updates, but from the user point of view there is only one update when the editor is closed.

Categories

Resources