Reputation: 619
I have text file which is being been used by modscan to write data into the file. At a particular time I have to read the data and save in database. In offline mode ie; without modscan using it I can read the data and very well save in database. however as it online with modscan it gives exception
Cannot access file as it been used by other process.
My code:
using System.IO;
string path = dt.Rows[i][11].ToString();
string[] lines = System.IO.File.ReadAllLines(@path);
path has "E:\Metertxt\02.txt"
So what changes I need to make in order to read it without interfering with modscan. I googled and I found this which might work, however I am not sure how to use it
FileShare.ReadWrite
Upvotes: 0
Views: 2623
Reputation: 2309
You can use a FileStream
to open a file that is already open in another application. Then you'll need a StreamReader
if you want to read it line by line. This works, assuming a file encoding of UTF8:
using (var stream = new FileStream(@"c:\tmp\locked.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something with line, e.g. add to a list or whatever.
Console.WriteLine(line);
}
}
}
Alternative in case you really need a string[]
:
var lines = new List<string>();
using (var stream = new FileStream(@"c:\tmp\locked.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
}
}
// Now you have a List<string>, which can be converted to a string[] if you really need one.
var stringArray = lines.ToArray();
Upvotes: 3
Reputation: 1255
FileStream fstream = new FileStream("@path", FileMode.Open,FileAccess.Read, FileShare.ReadWrite);
StreamReader sreader = new StreamReader(fstream);
List<string> lines = new List<string>();
string line;
while((line = sreader.ReadeLine()) != null)
lines.Add(line);
//do something with the lines
//if you need all lines at once,
string allLines = sreader.ReadToEnd();
Upvotes: 0