Reputation: 739
I know that there are some good answers for this problem, but in my case I think there is something special:
In my C# project (running on a server) I want to read the content of a file that is on a remote CNC machine's IPC. I open a new connection with credentials and try to read the content with File.ReadAllLines. I could read many other files from that machine without problem. But on this file I get each time "The process cannot access the file ... because it is being used by another process"
The remote CNC machine is writing to the file as soon as a new Alarm message on the CNC machine occurs. So this writing is not frequently. (Perhaps 1-2 times an hour). I have no information how the CNC machine writes to the file (if it is closing the file after wrting), and I have also no chance to change and optimize this process.
I see also no other client that is trying to read from the same file. Also in my own app there is no other code that is trying to acces the file.
There is also one strange point: If I map a network drive from my server and open the file manualy, it can be opened without any problem. I do not get a similar Error message like "...File is in use".
My code is like below. My target is to read the file content line by line. How can I overcome this problem?
public void Read_Alarm_Log_File()
{
string networkPath = "\\\\" + TagService.IP_Win_List + "\\F$";
NetworkCredential credentials = new NetworkCredential("username", "XXXXX");
TagService.Alarm_log_File_content.Clear();
try
{
using (new NetworkConnection(networkPath , credentials))
{
var lines = File.ReadAllLines(networkPath + "\\mmc2\\proto.txt");
for (var i = 0; i < lines.Length; i += 1)
{
var line = lines[i] + "\n";
TagService.Alarm_log_File_content.Add(line);
}
}
}
catch (Exception ex)
{
using (StreamWriter sw = File.AppendText((CommonClass.error_path)))
{
sw.WriteLine("Alarm Log File could not be read: " + ex + " " + Convert.ToString(DateTime.Now));
}
}
}
Upvotes: 0
Views: 102