Read log file being used by another process - c#

Goal
I want to press a button on my GUI and read in the seclog.log file (symantec AV log) from a remote machine and display the contents of the log to a rich text box in my application.
Things That Work
everything but reading the log file
Error Message
System.IO.IOException was unhandled
Message=The process cannot access the file '\\HOSTNAME\C$\Program Files (x86)\Symantec\Symantec Endpoint Protection\seclog.log' because it is being used by another process.
Source=mscorlib
code
//possible seclog paths
String seclogPath1 = #"\\\\" + target + "\\C$\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\seclog.log";
String seclogPath2 = #"\\\\" + target + "\\C$\\Program Files\\Symantec\\Symantec Endpoint Protection\\seclog.log";
//if seclog exists
if (File.Exists(seclogPath1))
{
//output.AppendText("file exists at " + seclogPath1);
//var seclogContent = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Stream stream = File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);
string str = streamReader.ReadToEnd();
output.AppendText(str);
streamReader.Close();
stream.Close();
}
Things I've Tried
File is being used by another process
C# The process cannot access the file ''' because it is being used by another process
Googling the issue
using filestreams in multiple ways

//possible seclog paths
String seclogPath1 = #"\\\\" + target + "\\C$\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\seclog.log";
String seclogPath2 = #"\\\\" + target + "\\C$\\Program Files\\Symantec\\Symantec Endpoint Protection\\seclog.log";
//if seclog exists
if (File.Exists(seclogPath1))
{
//output.AppendText("file exists at " + seclogPath1);
//var seclogContent = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Stream stream = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);
string str = streamReader.ReadToEnd();
output.AppendText(str);
streamReader.Close();
stream.Close();
}
what i had to change
i had to create a readwrite filestream
original code
Stream stream = File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);
new code
Stream stream = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);

using (StreamReader sr = new StreamReader(filePath, true))
{
sr.Close(); //This is mandatory
//Do your file operation
}

Related

Read file that's already used by another process

I have a C# app that tries to read a log file which is being written to by another app. When I try to read the file, I get IOException
"The process cannot access the file ... because it is being used by
another process."
What I tried using so far are the following, but none of them fix the problem
var log = File.ReadAllText(logPath);
var stream = new FileStream(logPath, FileMode.Open);
using (var stream = File.Open(logPath, FileMode.Open))
{
}
try this:
FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader logFileReader = new StreamReader(logFileStream);
while (!logFileReader.EndOfStream)
{
string line = logFileReader.ReadLine();
// Your code here
}
// Clean up
logFileReader.Close();
logFileStream.Close();
edited with MethodMan's suggestions
using(FileStream logFileStream = new FileStream(#"c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using(StreamReader logFileReader = new StreamReader(logFileStream))
{
string text = logFileReader.ReadToEnd();
// Your code..
}
}
You can do nothing, if the "another app" does not use Share.Read while creating/opening the file.

System.IO.IOException being used by another process

I am trying to write to a file, I believe i am closing the file that i had read in earlier in the code, but I am getting a "System.IO.IO.Exception" This is my code for reading and writing to the file.
public class InOutTxt
{
public List<Employee> ReadFile(string fileName) {
FileStream fs = new FileStream(fileName,FileMode.Open ,FileAccess.ReadWrite);
StreamReader fileIn = new StreamReader(fileName);
fileIn = File.OpenText(fileName);
List<Employee> list = new List<Employee>();
string[] test;
string name;
string ID;
string dep;
string post;
while (!fileIn.EndOfStream || !File.Exists(fileName)) {
string inString = fileIn.ReadLine();
test = inString.Split('#');
name = test[0];
ID = test[1];
dep = test[2];
post = test[3];
Employee newEmp = new Employee(name, ID, dep, post);
list.Add(newEmp);
}
fileIn.Close();
fs.Close();
return list;
}
public void WriteFile(List<Employee> outList, string file) {
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite);
StreamWriter writeOut = new StreamWriter(file);
for (int i = 0; i < outList.Count; i++) {
writeOut.WriteLine(outList[i].name + '#' + outList[i].IDnum + '#' + outList[i].department + '#' + outList[i].position);
}
writeOut.Close();
fs.Close();
}
}
The Error is occuring at this part of the code
StreamReader fileIn = new StreamReader(fileName);
If it helps any it was running well earlier today, the only major change I have made was the addition of the FileStream attribute above.
System.IO.IOException being used by another process
You have opened file using the FileStream constructor and the StreamReader gives error when it tries to open the file again using the fileName constructor. Pass the FileStream object instead of fileName.
FileStream Constructor (String, FileMode)
The constructor is given read/write access to the file, and it is
opened sharing Read access (that is, requests to open the file for
writing by this or another process will fail until the FileStream
object has been closed, but read attempts will succeed), MSDN.
//File is opened by FileStream and not available for opening before it is closed.
FileStream fs = new FileStream(fileName,FileMode.Open ,FileAccess.ReadWrite);
StreamReader fileIn = new StreamReader(fs); //Here pass fs instead of fileName

Storing more than one value into Isolated Storage

I have created a isolated storage that only store one values and display one value of e.g. "aaaaaaaa,aaaaaaaa".
How can I make it so that it stores
1)"aaaaaaaa,aaaaaaaaa"
2)"bbbbbbbb,bbbbbbbbb"
3)"cccccccccc,cccccccccc"
Below shows codes that stores only one value:
//get the storage for your app
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
//define a StreamWriter
StreamWriter writeFile;
if (!store.DirectoryExists("SaveFolder"))
{
//Create a directory folder
store.CreateDirectory("SaveFolder");
//Create a new file and use a StreamWriter to the store a new file in
//the directory we just created
writeFile = new StreamWriter(new IsolatedStorageFileStream(
"SaveFolder\\SavedFile.txt",
FileMode.CreateNew,
store));
}
else
{
//Create a new file and use a StreamWriter to the store a new file in
//the directory we just created
writeFile = new StreamWriter(new IsolatedStorageFileStream(
"SaveFolder\\SavedFile.txt",
FileMode.Append,
store));
}
StringWriter str = new StringWriter();
str.Write(textBox1.Text);
str.Write(",");
str.Write(textBox2.Text);
writeFile.WriteLine(str.ToString());
writeFile.Close();
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
StringWriter str = new StringWriter();
str.Write(textBox1.Text);
str.Write(",");
str.Write(textBox2.Text);
writeFile.WriteLine(str.ToString());
writeFile.Close();
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
You can use WriteLine several times like below
writeFile.WriteLine(string.Format("{0},{1}", "aaaaa","aaaaa"));
writeFile.WriteLine(string.Format("{0},{1}", "bbbbb","bbbbb"));
writeFile.WriteLine(string.Format("{0},{1}", "ccccc","ccccc"));
I can confirm Damith's answer, and should be marked as so.
If you're wondering about reading the lines back in:
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("SaveFolder", FileMode.Open, store);
StreamReader reader = new StreamReader(stream);
string rdr = reader.ReadLine();
rdr will be a string representing the first line, you can then call ReadLine() again to get the next line, etc. The first call to ReadLine() will return the first line you wrote to the store.
Hope this is useful to you or anyone else working in this area.

IsolatedStorage in Window Phone 7.5

I am working with IsolatedStorage in Windows Phone 7.5. I am trying to read some text from a file. But the debugger says the operation is not permitted on IsolatedStorageFileStream. Why?
//Read the file from the specified location.
fileReader = new StreamReader(new IsolatedStorageFileStream("info.dat", FileMode.Open, fileStorage));
//Read the contents of the file (the only line we created).
string textFile = fileReader.ReadLine();
//Write the contents of the file to the MEssageBlock on the page.
MessageBox.Show(textFile);
fileReader.Close();
UPD my new code
object _syncObject = new object();
lock (_syncObject)
{
using (var fileStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (FileStream stream = new FileStream("/info.dat", FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new StreamReader(stream))
{
string textFile = reader.ReadLine();
MessageBox.Show(textFile);
}
}
}
}
}
Try this, it works for me: Hope it works for you too
String sb;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName))
{
StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, myIsolatedStorage));
sb = reader.ReadToEnd();
reader.Close();
}
if(!String.IsNullOrEmpty(sb))
{
MessageBox.Show(sb);
}
}
If this doesn't work, then maybe your file doesn't exist.
Normally when I've used isolated storage, I've done something like:
using (var stream = fileStorage.OpenFile("info.dat", FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
...
}
}
... rather than calling the constructor directly on IsolatedStorageFileStream. I can't say for sure whether that'll sort it out, but it's worth a try...
Just a guess:
WP emulator will reset all Isolatd Storage contents when it's closed
if you used FileMode.Open with a path to a non existing file you'll get Operation not permited exception.
You can use fileStorage.FileExists() to check if the file is there or use FileMode.OpenOrCreate.

I try to save many lines in a txt file using isolated storage in WP7 but it will only saves one, how do I save many?

I use this to save the score everytime the game is over
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
isf.CreateDirectory("Data");
StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("Data\\scoretest.txt", FileMode.Create, isf));
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " Score: " + punc);
sw.Close();
and to read from the txt I use a for that stops when the reading is null
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
StreamReader sr = null;
try
{
sr = new StreamReader(new IsolatedStorageFileStream(#"Data\scoretest.txt", FileMode.Open, isf));
for (;;)
{
string x = sr.ReadLine();
if (x == null)
break;
else
listBox1.Items.Add(x);
}
sr.Close();
}
catch
{
listBox1.Items.Add("");
}
It only charges the last line, Why it doesn't read more than one line?
FileMode.Create will overwrite the file every time. You should use FileMode.OpenOrCreate or FileMode.Append instead(ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx)
Also, take a look at the Isolated Storage Explorer tool to verify your file: http://msdn.microsoft.com/en-us/library/hh286408(v=VS.92).aspx

Categories