0

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

4

2 回答 2

3

您可以使用 aFileStream打开已在另一个应用程序中打开的文件。然后,StreamReader如果您想逐行阅读,则需要 a 。这有效,假设文件编码为 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);
        }
    }
}

如果你真的需要一个替代方案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();
于 2015-09-02T08:39:05.137 回答
0
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();
于 2015-09-02T08:39:53.747 回答