My application parses log files but when trying to parse the current day's file I get an error stating that the file is being used by another process. This log file is currently being written to and can be accessed through notepad but not through my application.
Current Code:
Stream stream = new FileStream(fileToRead, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(stream);
Also tried this but had no luck:
Stream stream = new FileStream(fileToRead, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
What changes need to be to my code in order to READ a file that is being used by another process. Copying the log file is not a solution due to the size of the log and performance of my application
We can use a different signature for opening the filestream with read/write access to other processes:
Stream stream = new FileStream(fileToRead, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite);
or
Stream stream = File.Open(fileToRead, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite);
The FileShare option determines how other processes can access the same file when this process opens the same file.
Your first code block will default to FileShare.None
:
Stream stream = new FileStream(fileToRead, FileMode.Open, FileAccess.Read);
This would fail whilst the file is open as it's trying to obtain exclusive access to the file.
However, you would need this to occur in the log writer to allow your log reader to have read access.
Lastly, try running your log reader as an administrator, as there may be operating system permissions at play that are not obvious when you "open with notepad".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With